所有用户都具有良好的角色和权限,因此他们无法访问该页面,并且错误 403 访问 拒绝 :
@SuppressWarnings("unchecked")
public Professor getConnectedProf() {
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String username;
if (principal instanceof UserDetails) {
username = ((UserDetails)principal).getUsername();
} else {
username = principal.toString();
}
Collection<SimpleGrantedAuthority> authorities = (Collection<SimpleGrantedAuthority>) SecurityContextHolder.getContext().getAuthentication().getAuthorities();
for (SimpleGrantedAuthority simpleGrantedAuthority : authorities) {
logger.info("the authorité for the current user is = " + simpleGrantedAuthority.getAuthority());
}
logger.info("this the username of the connected user : " + username);
return sp.getProfByMatricule(username);
}
这将返回这些值:
18:12:50.097 [http-nio-8080-exec-9] INFO c.o.m.AppInitializer#148 the authorité for the current user is = ADMIN
18:12:50.098 [http-nio-8080-exec-9] INFO c.o.m.AppInitializer#148 the authorité for the current user is = DEPCHEF
18:12:50.098 [http-nio-8080-exec-9] INFO c.o.m.AppInitializer#148 the authorité for the current user is = PROF
18:12:50.098 [http-nio-8080-exec-9] INFO c.o.m.AppInitializer#148 the authorité for the current user is = USER
18:12:50.099 [http-nio-8080-exec-9] INFO c.o.m.AppInitializer#151 this the username of the connected user : admin
我的security.xml是这样的:
<http auto-config="true">
<intercept-url pattern="/" access="hasRole('PROF')"/>
<intercept-url pattern="/index" access="hasAnyRole('PROF','ADMIN','DEPCHEF','CHEF')"/>
<intercept-url pattern="/mission" access="hasAnyRole('ADMIN','USER')"/>
<intercept-url pattern="/mission/*" access="hasAnyRole('ADMIN','USER')"/>
<intercept-url pattern="/addMission/*" access="hasRole('PROF')"/>
<form-login login-page="/login" default-target-url="/index" authentication-failure-url="/login?error" username-parameter="username" password-parameter="password"/>
<logout logout-success-url="/login?logout" />
</http>
当我尝试获取/ index时,我拒绝了403访问。
HTTP Status 403 – Forbidden
Type Status Report
Message Access is denied
Description The server understood the request but refuses to authorize it.
Apache Tomcat/9.0.36
答案 0 :(得分:1)
hasRole()
似乎不起作用。使用 hasAuthority()
对我有用,
答案 1 :(得分:0)
根据documentation,Spring Security 4
自动为任何角色加上ROLE_
前缀。因此,如果您指定以下内容:
<intercept-url pattern="/index" access="hasAnyRole('PROF','ADMIN','DEPCHEF','CHEF')"/>
这暗示着:
<intercept-url pattern="/index" access="hasAnyRole('ROLE_PROF','ROLE_ADMIN','ROLE_DEPCHEF','ROLE_CHEF')"/>
并且由于您的日志中没有ROLE_
前缀,因此说明403。
根据罗宾·温奇(Rob Winch)的解释here:
原因是因为权限不仅限于角色。 例如,您可以具有基于组的权限。 ROLE_是一种方法 区分权限的类型。
如果表达式声明为hasRole,则此约定应 由于用户明确指出这是一个 基于角色的权限。因此,问题在于您没有使用 ROLE_前缀。您可以按照迁移指南了解如何 解决你的问题 http://docs.spring.io/spring-security/site/docs/4.0.x/reference/htmlsingle/#m3to4 一种替代方法是使用hasAuthority代替hasRole。的 hasAuthority表达式有效,因为它并不意味着ROLE_被 附加到传入的值中。