Skip to main content
 首页 » 编程设计

Spring Security Basic 认证

2022年07月19日140txw1958

Spring Security Basic 认证#

本文介绍如何在spring security中搭建、配置、自定义Basic认证。读者需要在spring mvc 基础上进行配置测试。

Spring Security配置

使用java config方式配置如下:

@Configuration 
@EnableWebSecurity 
public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { 
  
    @Autowired 
    private MyBasicAuthenticationEntryPoint authenticationEntryPoint; 
  
    @Autowired 
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { 
        auth.inMemoryAuthentication() 
          .withUser("user1").password("user1Pass") 
          .authorities("ROLE_USER"); 
    } 
  
    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
        http.authorizeRequests() 
          .antMatchers("/securityNone").permitAll() 
          .anyRequest().authenticated() 
          .and() 
          .httpBasic() 
          .authenticationEntryPoint(authenticationEntryPoint); 
  
        http.addFilterAfter(new CustomFilter(), 
          BasicAuthenticationFilter.class); 
    } 
} 

对应xml配置如下:

<?xml version="1.0" encoding="UTF-8"?> 
<beans:beans xmlns="http://www.springframework.org/schema/security" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:beans="http://www.springframework.org/schema/beans" 
    xsi:schemaLocation=" 
        http://www.springframework.org/schema/security  
        http://www.springframework.org/schema/security/spring-security-3.1.xsd 
        http://www.springframework.org/schema/beans  
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd"> 
  
    <http pattern="/securityNone" security="none"/> 
    <http use-expressions="true"> 
        <intercept-url pattern="/**" access="isAuthenticated()" /> 
        <http-basic /> 
    </http> 
  
    <authentication-manager> 
        <authentication-provider> 
            <user-service> 
                <user name="user1" password="user1Pass" authorities="ROLE_USER" /> 
            </user-service> 
        </authentication-provider> 
    </authentication-manager> 
  
</beans:beans> 

当然推荐使用java config方式配置。

在主要配置元素里需关注的是元素,其对整个应用来说实现Basic认证是足够的。不是本文重点,所以我们使用内存方式存储管理用户和密码(明文方式)。

测试spring security应用程序

这里直接使用curl命令进行测试,windows平台可以使用git Bash。首先,我们不带任何安全凭证尝试访问/homepage.html。

curl -i http://localhost:8080/spring-security-mvc-basic-auth/homepage.html 

获得返回401 为认证信息:

HTTP/1.1 401 Unauthorized 
Server: Apache-Coyote/1.1 
Set-Cookie: JSESSIONID=E5A8D3C16B65A0A007CFAACAEEE6916B; Path=/spring-security-mvc-basic-auth/; HttpOnly 
WWW-Authenticate: Basic realm="Spring Security Application" 
Content-Type: text/html;charset=utf-8 
Content-Length: 1061 
Date: Wed, 29 May 2018 15:14:08 GMT 

如果在浏览器中访问,会拦截异常并使用简单对话框提示我们需要凭证,因为使用curl仅显示上述内容。

现在我们请求相同资源,但提供访问凭证:

curl -i --user user1:user1Pass http://localhost:8080/spring-security-mvc-basic-auth/homepage.html 

现在,服务器端响应状态为200,并带有Cookie:

HTTP/1.1 200 OK 
Server: Apache-Coyote/1.1 
Set-Cookie: JSESSIONID=301225C7AE7C74B0892887389996785D; Path=/spring-security-mvc-basic-auth/; HttpOnly 
Content-Type: text/html;charset=ISO-8859-1 
Content-Language: en-US 
Content-Length: 90 
Date: Wed, 29 May 2018 15:19:38 GMT 

从浏览器端应用可以被正常访问,唯一不同的是,登录页不是必须的,所有支持Basic认证的浏览器会使用对话框提示输入用户凭证。

进一步配置——入口点

缺省情况下spring security 提供BasicAuthenticationEntryPoint类针对401未认证情况,返回完整页面响应给客户端,在浏览器中html方式展示错误没有问题,但有些场景不适合,比如REST API,使用json方式返回更合适。

spring security提供了足够灵活方式支持新的需求,我们可以覆盖入口点:

<http-basic entry-point-ref="myBasicAuthenticationEntryPoint" /> 

新入口点定义为标准bean:

@Component 
public class MyBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint { 
  
    @Override 
    public void commence 
      (HttpServletRequest request, HttpServletResponse response, AuthenticationException authEx)  
      throws IOException, ServletException { 
        response.addHeader("WWW-Authenticate", "Basic realm="" + getRealmName() + """); 
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); 
        PrintWriter writer = response.getWriter(); 
        writer.println("HTTP Status 401 - " + authEx.getMessage()); 
    } 
  
    @Override 
    public void afterPropertiesSet() throws Exception { 
        setRealmName("Baeldung"); 
        super.afterPropertiesSet(); 
    } 
} 

现在我们直接自己写http响应,完全控制响应体内容。

总结

本文我们示例使用spring security 和 Basic认证方式保护web 页面访问。分别介绍xml方式和java config方式配置spring security,并通过curl命令访问应用进行测试。
最后我们通过定义入口点控制错误信息格式——使用json格式代替标准html 错误页。


本文参考链接:https://blog.csdn.net/neweastsun/article/details/80616161