这个问题在这里已有答案:
我有两个REST端点:
/noAuth/rest/sayHi
/rest/auth/getMsg
我想只登录/rest/auth/getMsg
并直接访问/noAuth/rest/sayHi
。
当我在WebSecurityConfigurerAdapter.configure(HttpSecurity http)
使用下面的模式
@EnableWebSecurity
@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("Java Techie")
.password("Password")
.roles("ADMIN");
auth
.inMemoryAuthentication()
.withUser("Basant")
.password("Password2")
.roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/rest/**").authenticated()
.anyRequest().permitAll()
.and()
.httpBasic();}
}
}
我只在/rest/auth/getMsg
中获得登录提示,但在/noAuth/rest/sayHi
中没有,这是预期的。
但是当我使用下面的模式时,我会在/rest/auth/getMsg
和/noAuth/rest/sayHi
中获得登录提示,这对我来说非常意外。
http
.authorizeRequests()
.anyRequest().authenticated()
.antMatchers("/rest/**").permitAll()
.and()
.httpBasic();`
我知道第二次我做错了什么,所以我想明白为什么我没有登录只有/rest/auth/getMsg
并直接访问/noAuth/rest/sayHi
。
更新
@nully它有一些意义,但打破了我对其他案例的理解。让我们说如果我使用这种模式:
http
.authorizeRequests()
.anyRequest().authenticated()
.anyRequest().hasRole("ADMIN")
.and()
.httpBasic();`
只允许user =“Java Techie”登录,因为它是ADMIN
并为user =“Basant”抛出403 Forbidden
。
但是当我使用时
http
.authorizeRequests()
.anyRequest().authenticated()
.antMatchers("/rest/**").hasRole("ADMIN")
.and()
.httpBasic();
根据你的解释,它不应该允许user =“Basant”访问/rest/auth/getMsg
,因为它有role =“USER”。但实际上它允许我在使用user =“Basant”时访问/rest/auth/getMsg
。
执行从左到右。在第一种情况下:.antMatchers(“/ rest /”)。authenticated(),所以验证匹配休息的任何东西/
在2种情况下:.anyRequest()。authenticated(),因此任何请求都将在前进之前获得所需的身份验证。
如果没有其他规则,则默认为要求身份验证。你应该添加像antMatchers("/noAuth/**").permitAll()
这样的东西。