簡體   English   中英

當匿名用戶嘗試經過身份驗證的操作時,更改 spring 安全登錄重定向

[英]Change spring security login redirect when anonymous user tries authenticated action

默認情況下,spring 安全將我的用戶重定向到 /login 當用戶未經過身份驗證並嘗試訪問需要角色的 url 時。 我怎樣才能改變這個? 我為 accessDenied 頁面添加了一個處理程序,但這僅在我的用戶已經登錄時才會執行。我怎樣才能為匿名用戶做同樣的事情? 這是我的 spring 安全配置:

 @Override
    protected void configure(final HttpSecurity http) throws Exception {
        http.sessionManagement()
            .and().authorizeRequests()
            //session routes
            .antMatchers("/login", "/register").anonymous()
            .antMatchers(HttpMethod.POST, "/user/verifyAccount/resend").hasRole("NOT_VERIFIED")
            .antMatchers("/user/verifyAccount/resendConfirmation").hasRole("NOT_VERIFIED")
            .antMatchers("/user/verifyAccount").hasRole("USER")
            .antMatchers("/logout").authenticated()

            //profile routes
            .antMatchers("/user/account").hasRole("USER")
            .antMatchers("/user/account/search", "/user/account/update",
                "/user/account/updateCoverImage", "/user/account/updateInfo",
                "/user/account/updateProfileImage").hasRole("VERIFIED")

            //jobs routes
            .antMatchers("/jobs/{id:[\\d]+}/contact").hasRole("VERIFIED")
            .antMatchers("/jobs/new").hasRole("PROVIDER")
            .antMatchers(HttpMethod.GET, "/jobs/{id:[\\d]+}").permitAll()
            .antMatchers(HttpMethod.POST, "/jobs/{id:[\\d]+}").hasRole("VERIFIED")

            //provider routes
            .antMatchers("/user/dashboard", "/user/dashboard/search").hasRole("PROVIDER")
            .antMatchers("/user/join", "/user/join/chooseCity").hasRole("VERIFIED")

            //else
            .antMatchers("/**").permitAll()

            .and().formLogin()
            .loginPage("/login")
            .usernameParameter("email")
            .passwordParameter("password")
            .successHandler(authenticationSuccessHandler())
            .defaultSuccessUrl("/user/account", false)
            .failureUrl("/login?error=true")

            .and().rememberMe()
            .rememberMeParameter("rememberMe")
            .userDetailsService(userDetailService)
            .key(FileCopyUtils.copyToString(new InputStreamReader(authKey.getInputStream())))
            .tokenValiditySeconds((int) TimeUnit.DAYS.toSeconds(30))

            .and().logout()
            .logoutUrl("/logout")
            .logoutSuccessUrl("/login")

            .and().exceptionHandling()
            .accessDeniedHandler(accessDeniedHandler())
            .and().csrf().disable();
    }

這是我的 accessDeniedHandler:

public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    public static final Logger LOGGER = LoggerFactory.getLogger(CustomAccessDeniedHandler.class);

    @Override
    public void handle(
        HttpServletRequest request,
        HttpServletResponse response,
        AccessDeniedException exc) throws IOException, ServletException {

        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null) {
            LOGGER.warn("User: " + auth.getName()
                + " attempted to access the protected URL: "
                + request.getRequestURI());
            Collection<SimpleGrantedAuthority> authorities = createAuthorities(Arrays.asList("VERIFIED"));
            if (!auth.getAuthorities().containsAll(authorities)) {
                response.sendRedirect(request.getContextPath() + "/user/account");
                return;
            }
        }

        response.sendRedirect(request.getContextPath() + "/");
    }

    private Collection<SimpleGrantedAuthority> createAuthorities(Collection<String> roles){
        return roles.
            stream()
            .map((role) -> new SimpleGrantedAuthority("ROLE_" + role))
            .collect(Collectors.toList());
    }

}

您正在使用.loginPage("/login")指定重定向 url 。 你可以在那里改變路線。 匿名用戶應該有權訪問您未指定需要具有.hasRole()角色的所有其他路由。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM