> For the complete documentation index, see [llms.txt](https://spring-boot.shujuwajue.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://spring-boot.shujuwajue.com/an-quan/spring-security/http-basicren-zheng.md).

# 认证

## Http Basic认证

示例

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

## 表单认证

```java
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

```java
@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

```java
@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());



    }

}
```
