使用Spring Security重定向页面时无法识别用户ROLE

时间:2017-08-16 10:43:37

标签: spring spring-security

我正在使用Spring security和Thymeleaf开展我的项目。我有基本的Spring Security集成。

SecurityConfig.java

import ast

inputs = []
while True:
    num = input("Enter a number: ")

    if num == "done" :
        break
    try:
        # Check if the input is a number
        if num.isnumeric():
            # If so, convert the string to a number
            number = ast.literal_eval(num)
            # If it's an int, store it in the list
            if isinstance(number, int):
                inputs.append(number)
            else:
                # If not, raise and exception
                raise ValueError("Not an integer!")

    except ValueError as ve:
        print(ve)

# Show the desired output
print("Maximum is", max(inputs))
print("Minumum is", min(inputs))

SecurityWebApplicationInitializer.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()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .defaultSuccessUrl("/success", true)
                .and()
            .httpBasic();
      } 
}

Controller.java

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

}

登录成功后,我的用户被重定向,但页面错误。我的用户有角色ROLE_USER但是方法 loginPageRedirect 将它重定向到页面index3,它应该是index2。我想我的用户角色无法识别。我怎样才能做到这一点?我应该将某些内容作为参数添加到 loginPageRedirect ,以便识别角色吗?

1 个答案:

答案 0 :(得分:1)

我找到了适用于我的解决方案。

我编辑了 loginPageRedirect 方法,如下所示:

@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() + "/index1"));                            
         }
         else if(role.contains("ROLE_USER")) {
             response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/index2"));
         }
    }

希望它可以帮助有同样问题的人:)