java 得到登陆用户的id,Spring OAuth2.0:根据客户端ID获取用户角色

I have multiple clients registered for my oauth2 auth server. lets say user1 have roles such as ROLE_A, ROLE_B for client1, same user has roes such as ROLE_C, ROLE_D for client2. now when the user logins either using client1 or client2 he is able to see all the four roles ie. ROLE_A, ROLE_B, ROLE_C and ROLE_D.

My requirement was when the user1 logins to client1 it should return only the roles ROLE_A and ROLE_B. when he logins using client2 it should return only ROLE_C and ROLE_D

For achieving this, what I planned is within the authenticate function, I need to get the clientId. so using the clientId and the username I can find the corresponding roles allocated to the user from the db (client-user-roles-mapping table). .But the issue is I don't know how to get the clientId within the authenticate function

@Override

public Authentication authenticate(final Authentication authentication) throws AuthenticationException {

String userName = ((String) authentication.getPrincipal()).toLowerCase();

String password = (String) authentication.getCredentials();

if (userName != null && authentication.getCredentials() != null) {

String clientId = // HERE HOW TO GET THE CLIENT ID

Set userRoles = authRepository.getUserRoleDetails(userName.toLowerCase(), clientId);

Collection authorities = fillUserAuthorities(userRoles);

Authentication token = new UsernamePasswordAuthenticationToken(userName, StringUtils.EMPTY, authorities);

return token;

} else {

throw new BadCredentialsException("Authentication Failed!!!");

}

} else {

throw new BadCredentialsException("Username or Password cannot be empty!!!");

}

}

Can anyone please help me on this

UPDATE 1

CustomAuthenticationProvider.java

@Component

public class CustomAuthenticationProvider implements AuthenticationProvider {

private final Logger log = LoggerFactory.getLogger(getClass());

@Autowired

private LDAPAuthenticationProvider ldapAuthentication;

@Autowired

private AuthRepository authRepository;

public CustomAuthenticationProvider() {

super();

}

@Override

public Authentication authenticate(final Authentication authentication) throws AuthenticationException {

String userName = ((String) authentication.getPrincipal()).toLowerCase();

String password = (String) authentication.getCredentials();

if (userName != null && authentication.getCredentials() != null) {

String clientId = // HERE HOW TO GET THE CLIENT ID

Set userRoles = authRepository.getUserRoleDetails(userName.toLowerCase(), clientId);

Collection authorities = fillUserAuthorities(userRoles);

Authentication token = new UsernamePasswordAuthenticationToken(userName, StringUtils.EMPTY, authorities);

return token;

} else {

throw new BadCredentialsException("Authentication Failed!!!");

}

} else {

throw new BadCredentialsException("Username or Password cannot be empty!!!");

}

}

public boolean invokeAuthentication(String username, String password, Boolean isClientValidation) {

try {

Map userDetails = ldapAuthentication.authenticateUser(username, password);

if(Boolean.parseBoolean(userDetails.get("success").toString())) {

return true;

}

} catch (Exception exception) {

log.error("Exception in invokeAuthentication::: " + exception.getMessage());

}

return false;

}

@Override

public boolean supports(Class extends Object> authentication) {

return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));

}

private Collection fillUserAuthorities(Set roles) {

Collection authorties = new ArrayList();

for(String role : roles) {

authorties.add(new SimpleGrantedAuthority(role));

}

return authorties;

}

}

解决方案

Here is you code after modification

@Override

public Authentication authenticate(final Authentication authentication) throws AuthenticationException {

String userName = ((String) authentication.getPrincipal()).toLowerCase();

String password = (String) authentication.getCredentials();

if (userName != null && authentication.getCredentials() != null) {

String clientId = getClientId();

// validate client ID before use

Set userRoles = authRepository.getUserRoleDetails(userName.toLowerCase(), clientId);

Collection authorities = fillUserAuthorities(userRoles);

Authentication token = new UsernamePasswordAuthenticationToken(userName, StringUtils.EMPTY, authorities);

return token;

} else {

throw new BadCredentialsException("Authentication Failed!!!");

}

} else {

throw new BadCredentialsException("Username or Password cannot be empty!!!");

}

private String getClientId(){

final HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

final String authorizationHeaderValue = request.getHeader("Authorization");

final String base64AuthorizationHeader = Optional.ofNullable(authorizationHeaderValue)

.map(headerValue->headerValue.substring("Basic ".length())).orElse("");

if(StringUtils.isNotEmpty(base64AuthorizationHeader)){

String decodedAuthorizationHeader = new String(Base64.getDecoder().decode(base64AuthorizationHeader), Charset.forName("UTF-8"));

return decodedAuthorizationHeader.split(":")[0];

}

return "";

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
OAuth 2.0 是一种用于授权的标准。在 OAuth 2.0 中,客户端应用程序通过向授权服务器发送请求来获取访问资源服务器上受保护的资源的权限。在本篇文章中,我们将学习如何使用 Java 实现 OAuth 2.0 的服务端与客户端。 服务端实现: 服务端实现主要包括以下步骤: 1. 配置授权服务器:在授权服务器上配置客户端应用程序所需的授权信息,例如客户端 ID客户端密钥等。 2. 实现授权端点:授权端点是授权服务器上的一个 URL,客户端应用程序将向此 URL 发送请求来获取访问令牌。 3. 实现令牌端点:令牌端点是授权服务器上的一个 URL,客户端应用程序将向此 URL 发送请求来获取访问令牌。 4. 实现资源服务器:资源服务器是受保护的服务器,客户端应用程序需要访问受保护的资源时,将向资源服务器发送请求,并提供有效的访问令牌。 客户端实现: 客户端实现主要包括以下步骤: 1. 注册应用程序:在授权服务器上注册客户端应用程序,并获取客户端 ID客户端密钥等信息。 2. 实现授权流程:客户端应用程序需要向授权服务器发送请求来获取访问令牌。授权流程通常包括以下步骤: a. 发送授权请求:客户端应用程序向授权服务器发送请求,请求授权访问受保护的资源。 b. 用户授权:如果用户尚未登录,则授权服务器会要求用户登录并授权。 c. 发送访问令牌请求:一旦用户授权,授权服务器会向客户端应用程序发送访问令牌。 d. 访问受保护的资源:客户端应用程序使用访问令牌访问受保护的资源。 以上是 OAuth 2.0 的服务端与客户端的实现步骤,具体实现可以参考开源框架,例如 Spring Security OAuth 等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值