我使用弹簧靴安全性来实现基本认证。下面是我的代码。绕过基于角色的授权,基本身份验证不起作用。在没有凭据的情况下,我的服务也给出了响应,不会引发任何错误。当我传递错误的凭据时,它也不会引发任何错误。如何修复此错误。有人可以建议吗?
var handler = new HttpClientHandler
{
UseDefaultCredentials = true,
PreAuthenticate = true
};
HttpClient = new HttpClient(handler);
HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
我的控制器类具有多个端点:
package com.agcs.cids.security;
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// Authentication : User --> Roles
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.inMemoryAuthentication().withUser("user1").password("Secret1").roles("USER");
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/id").hasAuthority("USER");
}
}
答案 0 :(得分:1)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.inMemoryAuthentication().withUser("user1").password("{noop}Secret1").roles("USER");
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/claims/id/").hasRole("USER")
.and()
.httpBasic();
}
}
/claims/id/
,而不是/id/
USER
定义为角色名称,而不是授权名称,因此要求hasRole()
httpBasic()
进行基本身份验证(10.10.2. Basic Authentication){noop}
答案 1 :(得分:0)
你快到了。
使用.antMatchers("/id/**").hasRole("USER");
代替.antMatchers("/id").hasAuthority("USER");
答案 2 :(得分:0)
尝试
http.csrf().disable().authorizeRequests()
.antMatchers("/id/**").hasAnyRole("USER").and()
.authorizeRequests().antMatchers("/").permitAll();