mic*_*euz 4 anonymous roles spring-security
我为用户提供了带有访问密钥的特殊URL.与简单的匿名用户相比,通过此特殊网址访问公共页面的用户应该能够看到一些额外的数据.
我想基于请求中提供的参数给匿名用户一些额外的角色,所以我可以在我的模板中做这样的事情:
<@sec.authorize ifAnyGranted="ROLE_ADMIN, ROLE_USER, ROLE_INVITED_VISITOR">
...some additional stuff for invited user to see
</@sec.authorize>
Run Code Online (Sandbox Code Playgroud)
目前我正在实施Spring的OncePerRequestfilter:
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
if (null != request.getParameter("accessKey")) {
if(isValid(request.getParameter("accessKey"))) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
//how do i add additional roles to authenticated (potentially anonymous) user?
}
}
}
Run Code Online (Sandbox Code Playgroud)
为什么不创建一个委托给原始的包装类,但添加了几个额外的GrantedAuthorities:
public class AuthenticationWrapper implements Authentication
{
private Authentication original;
private GrantedAuthority[] extraRoles;
public AuthenticationWrapper( Authentication original, GrantedAuthority[] extraRoles )
{
this.original = original;
this.extraRoles = extraRoles;
}
public GrantedAuthority[] getAuthorities()
{
GrantedAuthority[] originalRoles = original.getAuthorities();
GrantedAuthority[] roles = new GrantedAuthority[originalRoles.length + extraRoles.length];
System.arraycopy( originalRoles, 0, roles, 0, originalRoles.length );
System.arraycopy( extraRoles, 0, roles, originalRoles.length, extraRoles.length );
return roles;
}
public String getName() { return original.getName(); }
public Object getCredentials() { return original.getCredentials(); }
public Object getDetails() { return original.getDetails(); }
public Object getPrincipal() { return original.getPrincipal(); }
public boolean isAuthenticated() { return original.isAuthenticated(); }
public void setAuthenticated( boolean isAuthenticated ) throws IllegalArgumentException
{
original.setAuthenticated( isAuthenticated );
}
}
Run Code Online (Sandbox Code Playgroud)
然后在您的过滤器中执行此操作:
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
GrantedAuthority extraRoles = new GrantedAuthority[2];
extraRoles[0] = new GrantedAuthorityImpl( "Role X" );
extraRoles[1] = new GrantedAuthorityImpl( "Role Y" );
AuthenticationWrapper wrapper = new AuthenticationWrapper( auth, extraRoles );
SecurityContextHolder.getContext().setAuthentication( wrapper );
Run Code Online (Sandbox Code Playgroud)
现在,您的版本将使用额外角色替换身份验证.注意您可能必须处理尚未验证身份验证的情况,因此其getAuthorities()返回null.(包装器实现当前假定它总是从其包装的身份验证中获取非空数组)
| 归档时间: |
|
| 查看次数: |
10243 次 |
| 最近记录: |