使用 Spring security 和 Thymeleaf 根据角色重定向页面 - Spring [英] Page redirecting depending on Role using Spring security and Thymeleaf - Spring

查看:33
本文介绍了使用 Spring security 和 Thymeleaf 根据角色重定向页面 - Spring的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Spring security 和 Thymeleaf 处理我的项目.我有基本的 Spring Security 集成.

I am working on my project with Spring security and Thymeleaf. I have basic Spring Security integration.

SecurityConfig.java

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    private DataSource dataSource;

    @Autowired
      public void configureGlobal (AuthenticationManagerBuilder auth) throws Exception
      {
        auth
          .jdbcAuthentication()
            .dataSource(dataSource);
      }

    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
              .antMatchers("/login").permitAll()
              .antMatchers("/classesTable").hasRole("ADMIN")
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")

                .and()
            .httpBasic();
      } 
}

SecurityWebApplicationInitializer.java

public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer
{
    public SecurityWebApplicationInitializer(){
        super(SecurityConfig.class);
    }

}

在我的项目中,我有三个角色:学生、教授和管理员.我想要实现的是当我的学生登录时,他被重定向到页面 indexUser.html.当我的教授登录时,他被重定向到 indexProfesor.html,当管理员登录时,他会登陆 indexAdmin.html 页面.

In my project I have three roles: student, professor and admin. What I would like to achieve is when my student logs in that he is redirected to page indexUser.html. When my professor logs in he is redirected to indexProfesor.html and when admin does he lands on indexAdmin.html page.

我想到了这样的事情

if(role.contains("ROLE_ADMIN")){
      //redirect from here to indexAdmin.html

    }else if(role.contains("ROLE_USER")) {
        //redirect to indexUser.html
    }else
        //redirect to indexProfesor.html
}

但我不知道整个控制器应该是什么样子.

But I don't have picture how whole controller should look like.

让我的 homeContorller 看起来像这样:

Have my homeContorller that looks like this:

@Controller
public class HomeController {

   @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String loginPage(Model model) {
        return "login";
    }
}

我也将此代码添加到我的 index.html

Also I added this code to my index.html

<span sec:authorize="isAuthenticated()">
<span sec:authentication="name"></span>
| Roles: <span sec:authentication="principal.authorities"></span> |

所以我熟悉我的登录用户所拥有的角色.这里也是我的 login.html 的代码

So I am familiar with role that my logged user has. Here is also code for my login.html

<form  th:action="@{/login}" method="post" class="l-form">
  <input type="text" name="username"/>
  <input type="password" name="password"/>
  <input type="hidden" th:name="${_csrf.parameterName}" 
   th:value="${_csrf.token}" />

   <button type="submit" class="btn">Sign in!</button>
</form>

推荐答案

已找到适合我的解决方案.

Have found solution that works for me.

我将 http.formLogin().defaultSuccessUrl("/success", true) 添加到我的 SpringConfig 文件中.

I added http.formLogin().defaultSuccessUrl("/success", true) to my SpringConfig file.

看起来像这样

protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
              .antMatchers("/login").permitAll()
              .antMatchers("/classesTable").hasRole("ADMIN")
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .defaultSuccessUrl("/success", true)
                .and()
            .httpBasic();
      }

然后我在 HomeController 中创建了一个名为 loginPageRedirect

Then I made new method in HomeController called loginPageRedirect

@Controller
public class HomeController {

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String loginPage(Model model) {
        return "login";
    }
    
    @RequestMapping("/success")
    public void loginPageRedirect(HttpServletRequest request, HttpServletResponse response, Authentication authResult) throws IOException, ServletException {
        
        String role =  authResult.getAuthorities().toString();
        
        if(role.contains("ROLE_ADMIN")){
         response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/indexAdmin"));                            
         }
         else if(role.contains("ROLE_USER")) {
             response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/indexUser"));
         }
    }

}

希望对遇到同样问题的人有所帮助.

Hope it helps someone with same issue.

这篇关于使用 Spring security 和 Thymeleaf 根据角色重定向页面 - Spring的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆