gpt4 book ai didi

java - Spring Security 为 Authentication.getPrincipal() 返回 guest 而不是 UserDetails

转载 作者:行者123 更新时间:2023-11-30 11:55:01 28 4
gpt4 key购买 nike

我正在尝试实现 spring security 3.1.0.M1,但我无法让我的应用程序将 Authentication.getPrincipal 设置为我的自定义 UserDetails 实现。当我尝试获取登录用户时,它总是返回“guest”主体。请参阅下面的 getLoggedInUser 方法。

在 Users.java(UserDetails impl)中,getAuthorities 方法永远不会被调用,也许这就是为什么没有分配 user_role 的原因。

也许我配置错误了……我附上了我的实现大纲,希望有人能发现我的错误。感谢您的协助!

public static Users getLoggedInUser() {
Users user = null;
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null && auth.isAuthenticated()) {
Object principal = auth.getPrincipal();
if (principal instanceof Users) {
user = (Users) principal;
}
}
return user;
}

安全上下文文件(删除了 xml 和模式定义):

<global-method-security secured-annotations="enabled">
</global-method-security>
<http security="none" pattern="/services/rest-api/1.0/**" />
<http security="none" pattern="/preregistered/**" />
<http access-denied-page="/auth/denied.html">
<intercept-url
pattern="/**/*.xhtml"
access="ROLE_NONE_GETS_ACCESS" />
<intercept-url
pattern="/auth/**"
access="ROLE_ANONYMOUS,ROLE_USER" />
<intercept-url
pattern="/auth/*"
access="ROLE_ANONYMOUS" />
<intercept-url
pattern="/**"
access="ROLE_USER" />
<form-login
login-processing-url="/j_spring_security_check.html"
login-page="/auth/login.html"
default-target-url="/registered/home.html"
authentication-failure-url="/auth/login.html?_dc=45" />
<logout logout-url="/auth/logout.html"
logout-success-url="/" />
<anonymous username="guest" granted-authority="ROLE_ANONYMOUS"/>
<remember-me user-service-ref="userManager" key="valid key here"/>
</http>
<!-- Configure the authentication provider -->
<authentication-manager>
<authentication-provider user-service-ref="userManager">
<password-encoder ref="passwordEncoder" />
</authentication-provider>
</authentication-manager>

用户详细信息实现(Users.java):

public class Users implements Serializable, UserDetails {
public Collection<GrantedAuthority> getAuthorities() {
List<GrantedAuthority> auth = new ArrayList<GrantedAuthority>();
auth.add(new GrantedAuthorityImpl("ROLE_USER"));
return auth;
}

user-service-ref="userManager"(UserManagerImpl.java):

 public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
Users user = null;
try {
user = userDAO.findByUsername(username);
} catch (DataAccessException ex) {
throw new UsernameNotFoundException("Invalid login", ex);
}
if (user == null) {
throw new UsernameNotFoundException("User not found.");
}
return user;
}

最佳答案

你没有在这一行收到编译错误:auth.add("ROLE_USER");

我认为应该是:auth.add(new SimpleGrantedAuthority("ROLE_USER"));

关于java - Spring Security 为 Authentication.getPrincipal() 返回 guest 而不是 UserDetails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5256955/

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