认证

Http Basic认证

示例

http.httpBasic()
.and()
.csrf().disable()
.authorizeRequests()
.antMatchers("/login.html", "/auth").permitAll()
.anyRequest().authenticated()

表单认证

http.formLogin()
.loginPage("/login.html")
.loginProcessingUrl("/auth")
.usernameParameter("user")
.passwordParameter("pass")
.successHandler(bookShopAuthenticationSuccessHandler)
.failureHandler(bookShopAuthenticationFailureHandler)
.and()
.csrf().disable()
.authorizeRequests()
.antMatchers("/login.html", "/auth").permitAll()
.anyRequest().authenticated()

loginPage 自定义登录页面

除了登录注册页面其他页面都需要身份认证

指定用户名密码 字段name

successHandler,failureHandler 处理成功失败的handle

successHandler

@Component("bookShopAuthenticationSuccessHandler")
public class BookShopAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    /* (non-Javadoc)
     * @see org.springframework.security.web.authentication.AuthenticationSuccessHandler#onAuthenticationSuccess(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.Authentication)
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
            Authentication authentication) throws IOException, ServletException {
        System.out.println((UserDetails)authentication.getPrincipal());
        super.onAuthenticationSuccess(request, response, authentication);
    }

}

failureHandler

@Component("bookShopAuthenticationFailureHandler")
public class BookShopAuthenticationFailureHandler implements AuthenticationFailureHandler {

    /* (non-Javadoc)
     * @see org.springframework.security.web.authentication.AuthenticationFailureHandler#onAuthenticationFailure(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.AuthenticationException)
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException exception) throws IOException, ServletException {

        response.getWriter().print(exception.getMessage());



    }

}

Last updated