我想为我的Spring REST应用程序提供基于令牌的授权,该应用程序目前基于基本身份验证。
我该怎么做? (春季4.x)
答案 0 :(得分:1)
如果您使用的是基本身份验证流程,则必须向请求提供授权标头。
例如,如果您有user = theuser和password = mypassword,则标题将为
Key =授权;值=基本dGhldXNlcjpteXBhc3N3b3Jk
其中Basic之后的字符串是编码字符串,用户名:mypassword,是base64。 (查看此https://www.base64encode.org/)
此标头必须用于BasicAuthentication保护的端点。
实施的一个例子:
@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种会话模式:
答案 1 :(得分:0)
虽然这里的Spring入门指南 - https://spring.io/guides/gs/securing-web/与Spring Boot有关。它非常适用于基本的Spring 4.x