Spring安全性使用令牌授权进行基本身份验证

问题描述 投票:0回答:2

我想为我的Spring REST应用程序提供基于令牌的授权,该应用程序目前基于基本身份验证。

  1. 登录/令牌请求(POST / path / to / login)=>执行基本身份验证并返回令牌
  2. 所有其他请求=>执行令牌身份验证

我怎样才能做到这一点? (春季4.x)

spring spring-mvc spring-security
2个回答
1
投票

如果您使用的是基本身份验证流,则必须向请求提供Authorization标头。

例如,如果您有user = theuser和password = mypassword,则标题将为

关键=授权;值=基本dGhldXNlcjpteXBhc3N3b3Jk

Basic之后的字符串是编码字符串,用户名:mypassword,是base64。 (查看此https://www.base64encode.org/

此标头必须用于BasicAuthentication保护的端点。

实施的一个例子:

  1. 依赖性:https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-security
  2. 您必须创建配置类并添加注释:

@Configuration @EnableWebSecurity

public class MyWebSecurityCofiguration extends WebSecurityConfigurerAdapter{

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("theuser").password("mypassword").roles("ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.authorizeRequests()
            .antMatchers("/path/login").permitAll()
            .antMatchers("/**").hasRole("ADMIN").and().httpBasic();
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}

Stateless用于不创建会话,用户必须在每次请求时发送Authorization标头。还有其他3种会话模式:

  • always - 如果一个会话尚不存在,将始终创建一个会话
  • ifRequired - 仅在需要时创建会话(默认)
  • never - 框架永远不会创建会话本身,但如果它已经存在,它将使用一个

0
投票

虽然这里的Spring入门指南 - https://spring.io/guides/gs/securing-web/与Spring Boot有关。它非常适用于基本的Spring 4.x.

© www.soinside.com 2019 - 2024. All rights reserved.