Spring Security 基本认证

1. 概述

本教程将解释如何使用 Spring设置、配置和自定义基本身份验证。我们将在简单的Spring MVC 示例之上构建,并使用 Spring Security 提供的 Basic Auth 机制保护 MVC 应用程序的 UI。

2. Spring Security配置

我们可以使用 Java 配置来配置 Spring Security:

@Configuration
@EnableWebSecurity
public class CustomWebSecurityConfigurerAdapter {

    @Autowired private MyBasicAuthenticationEntryPoint authenticationEntryPoint;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
          .inMemoryAuthentication()
          .withUser("user1")
          .password(passwordEncoder().encode("user1Pass"))
          .authorities("ROLE_USER");
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/securityNone")
            .permitAll()
            .anyRequest()
            .authenticated()
            .and()
            .httpBasic()
            .authenticationEntryPoint(authenticationEntryPoint);
        http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class);
        return http.build();
    }
    
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

在这里,我们使用httpBasic()元素在SecurityFilterChain bean中定义基本身份验证*。*

我们也可以使用 XML 获得相同的结果:

<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="{noop}user1Pass" authorities="ROLE_USER" />
        </user-service>
    </authentication-provider>
</authentication-manager>

这里相关的是配置的主要<http>元素内的<http-basic>元素。这足以为整个应用程序启用基本身份验证。由于我们在本教程中不关注身份验证管理器,因此我们将使用内存管理器,其用户和密码以纯文本形式定义。

启用 Spring Security 的 Web 应用程序的web.xml已经在Spring Logout 教程中讨论过。

3. 使用受保护的应用程序

curl命令是我们使用安全应用程序的首选工具。

首先,让我们尝试在不提供任何安全凭证的情况下请求/homepage.html

curl -i http://localhost:8080/spring-security-rest-basic-auth/api/foos/1

我们得到预期的401 UnauthorizedAuthentication Challenge

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 2013 15:14:08 GMT

通常浏览器会解释这个质询并通过一个简单的对话框提示我们输入凭据,但由于我们使用的是curl,所以情况并非如此。

现在让我们请求相同的资源,主页,但也提供访问它的凭据:

curl -i --user user1:user1Pass 
  http://localhost:8080/spring-security-rest-basic-auth/api/foos/1

结果,来自服务器的响应是200 OK以及一个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 2013 15:19:38 GMT

从浏览器,我们可以正常使用应用程序;唯一的区别是登录页面不再是硬性要求,因为所有浏览器都支持基本身份验证,并使用对话框提示用户输入凭据。

4. 进一步配置 — 入口点

默认情况下,Spring Security 提供的BasicAuthenticationEntryPoint会向客户端返回401 Unauthorized响应的完整页面。错误的这种 HTML 表示在浏览器中呈现良好。相反,它不太适合其他场景,例如可能首选 json 表示的 REST API。

名称空间也足够灵活,可以满足这一新要求。为了解决这个问题,入口点可以被覆盖:

<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 响应,我们现在可以完全控制响应主体的格式。

5. Maven 依赖

之前在Spring Security with Maven 文章中讨论了 Spring Security 的 Maven 依赖项。我们需要在运行时同时使用spring-security-webspring-security-config

6. 结论

在本文中,我们使用 Spring Security 和 Basic Authentication 保护了一个 MVC 应用程序。我们讨论了 XML 配置,并使用简单的 curl 命令使用了应用程序。最后,我们控制了确切的错误消息格式,从标准的 HTML 错误页面移动到自定义文本或 JSON 格式。

可以在GitHub 项目中找到本文的完整实现。这是一个基于 Maven 的项目,因此它应该很容易导入并按原样运行。

当项目在本地运行时,可以在以下位置访问示例 HTML:

http://localhost:8080/spring-security-rest-basic-auth/api/foos/1

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值