# 认证

## 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());



    }

}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://spring-boot.shujuwajue.com/an-quan/spring-security/http-basicren-zheng.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
