【发布时间】:2020-02-23 01:02:55
【问题描述】:
我想知道是否有办法提供两种不同类型的身份验证?
用户应使用基本身份验证登录、注册、获取端点/login、/register、/user 的用户数据。当我调用 /api 时,它只能使用标头中提供的 JWT 令牌进行身份验证。
但是当我打电话给/api 时,我会在没有任何身份验证的情况下获得所有数据。当用户登录并调用/user 时,API 让 JWT 访问/api。
我的代码:
基本认证配置:
@Configuration
@EnableWebSecurity
@Order(1)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf().disable();
http
.authorizeRequests()
.antMatchers("/user").authenticated()
.antMatchers("/register").permitAll()
.and()
.formLogin().permitAll()
.defaultSuccessUrl("/user");
}
JWT 身份验证配置:
@Configuration
@Order(2)
public class JWTSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.antMatcher("/api/**")
.addFilterAfter(new JWTAuthorizationFilter(),UsernamePasswordAuthenticationFilter.class)
.authorizeRequests()
.anyRequest().authenticated()
.and()
.httpBasic().disable();
}
【问题讨论】:
-
我关注了 spring 文档 (docs.spring.io/spring-security/site/docs/current/reference/…) 但我不知道我的代码有什么问题,
-
如果您想对每个请求进行身份验证,您必须禁用 HTTP 会话。
标签: java spring spring-security