gpt4 book ai didi

java - Spring : how to apply role to existing JWT token

转载 作者:行者123 更新时间:2023-12-01 19:36:55 25 4
gpt4 key购买 nike

在 SingleSignOn(SSO)中,当应用程序加载时,我从我的办公室网络获取 jwt 不记名 token ,基本上我已经在其余 Web 服务中编写了代码,以从不同的 Web 服务获取不记名 token 。

我想要的是:我想在 Spring 确保其他一些端点的安全?我怎样才能做到这一点!

我不想提供登录名和密码表单来重新登录。因为我已经在调用网络服务来获取用户信息和不记名 token 。这意味着我已经登录,并且可以打印用户信息。

我有带有 userId 的用户角色表,我只想将表中可用的角色应用于登录的用户 ID。

我们该怎么做?

我发现了这个,但我希望这不会要求再次重新输入用户名和密码 https://www.ekiras.com/2016/04/authenticate-user-with-custom-user-details-service-in-spring-security.html

https://stackoverflow.com/a/11314388/1684778类似我的问题 https://stackoverflow.com/a/12057327/1684778

最佳答案

这里有很多事情需要考虑

用户身份验证:验证用户凭据后,我们将用户标记为已通过身份验证,并将其注册到 SecurityContext

您必须使用AuthenticationProvider来验证收到的 token 。

例如:

public class SSOAuthenticationProvider implements AuthenticationProvider {

public Authentication authenticate(Authentication authentication) {

// verified the authentication token
authentication.setAuthenticated(true);

// make the database call, get roles for the user
authentication.setAuthorities(<authorities - discussed below>);
SecurityContextHolder.getContext().setAuthentication(authentication);

return authentication;
}
}

权限:用户通过身份验证后,我们需要获取用户授予的权限并进行设置。为此,我们需要一个自定义类来代表授予的权限。

public class CustomAuthority implements GrantedAuthority {

private String role;

public CustomAuthority(String role) {
this.role = role;
}

@Override
public String getAuthority() {
return role;
}
}

我们根据从数据库收到的角色创建这些自定义权限实例。因此,在之前的 SSOAuthenticationProvider 中,我们执行以下操作

// make the database call, get roles for the user
List<String> roles = <db call to get roles>
authentication.setAuthorities(Collections.unmodifiableCollection(roles.stream().map(CustomAuthority::new).collect(Collectors.toList()));
SecurityContextHolder.getContext().setAuthentication(authentication);

这会导致当前经过身份验证的用户拥有他们有权担任的所有角色。

唯一待处理的步骤是对每个端点的权限/角色进行硬编码。现在,当用户身份验证过程完成并执行端点验证时,Spring 会查看当前端点所需的权限,并在当前经过身份验证的用户中查找它们。如果存在,则执行端点代码。如果不是,则抛出AccessDeniedException

关于java - Spring : how to apply role to existing JWT token,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59207288/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com