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

时间:2016-02-28 11:42:58

标签: spring spring-mvc spring-security

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

  1. 登录/令牌请求(POST / path / to / login)=>执行基本身份验证并返回令牌
  2. 所有其他请求=>进行令牌认证
  3. 我该怎么做? (春季4.x)

2 个答案:

答案 0 :(得分:1)

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

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

  

Key =授权;值=基本dGhldXNlcjpteXBhc3N3b3Jk

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

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

实施的一个例子:

  1. 相关性: https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-security
  2. 您必须创建配置类并添加注释:
  3. @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种会话模式:

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

答案 1 :(得分:0)

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