如果用户登录并尝试打开登录页面,如何打开主页?(Spring security)

时间:2016-07-19 05:40:40

标签: java spring-security spring-boot

我在项目中使用spring security,我使用自定义authonticate。我从代码中保存用户。

@Override
    public void saveUser(AuthLkUser lkUser) {
        final List<GrantedAuthority> grantedAuths = new ArrayList<>();
        GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_USER");
        grantedAuths.add(grantedAuthority);
        UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(lkUser.getMsisdn(), lkUser.getPricePlan(), grantedAuths);
        SecurityContextHolder.getContext().setAuthentication(result);
    }

它正常工作。但是在succsessufull登录后,我可以再次打开登录页面。 我需要在succsessufull登录后禁用可能性打开登录页面。我试过这个:

.antMatchers("/login", "/default/login").access("hasRole('ANONYMOUS')")

但具有“USER”角色的用户也可以打开登录页面。

我试过

@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication auth) throws IOException, ServletException {
        // initialization logic after login

        // redirect
        HttpSession session = request.getSession();
        SavedRequest savedReq = (SavedRequest) session.getAttribute("SAVED_REQUEST");
        if (savedReq == null) {
            response.sendRedirect(request.getContextPath() + "/landing");
        }
        else {
            response.sendRedirect(savedReq.getRedirectUrl());
        }
    }
}

并设置为配置

@Autowired
    private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;

.successHandler(myAuthenticationSuccessHandler)

但是在succsessufull登录后这个方法没有调用。

如果用户登录并尝试打开登录页面,如何打开主页?

为什么我的myAuthenticationSuccessHandler没有被调用?

这是我的配置

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/", "/index").access("hasRole('USER')")
//                .antMatchers("/login", "/default/login").access("hasRole('ANONYMOUS')")
                .and()
                .formLogin()
                .loginPage("/login")
                .loginProcessingUrl("/j_spring_security_check")
                .successHandler(myAuthenticationSuccessHandler)
                .permitAll();
        http.csrf()
                .disable()
                .authorizeRequests()
                .antMatchers("/resources/**", "/**").permitAll()
                .anyRequest().permitAll()
                .and();
    }
}

1 个答案:

答案 0 :(得分:0)

我认为您需要添加一个控制器,您需要在其中检查用户是否已登录的登录请求。如果没有登录,则显示登录页面,否则重定向到主页。以下是这样的样本控制器:

@Controller
@RequestMapping("/")
public class IndexController {

    @RequestMapping(value="/login",method = RequestMethod.GET)
    public String index(){

        if(SecurityUtils.isUserLoggedIn())
            return "redirect:/home"; 

        return "login";

    }

}

以下是示例SecurityUtils.java类,它是一个实用程序类,具有检查用户是否已登录的方法:

public class SecurityUtils {

    public static boolean isUserLoggedIn(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(null != authentication){
            return (authentication.isAuthenticated() && !(authentication instanceof AnonymousAuthenticationToken));
        }else{
            return false;
        }

    }
}
相关问题