簡體   English   中英

Spring 安全性 - 使用用戶名驗證用戶

[英]Spring Security - Authenticate user with username

我只想用用戶名驗證用戶。 為了實現這一點,我仍在使用UsernamePasswordAuthenticationToken但也傳遞了附加權限。
這是代碼:

List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
Authentication authentication = authenticationManager.authenticate(
    new UsernamePasswordAuthenticationToken(username,null,authorities)
);

不幸的是,這會引發錯誤的憑據異常。 我在這里想念什么?
用正確的用戶名密碼替換上面的代碼時,它可以完美運行。

Authentication authentication = authenticationManager.authenticate(
    new UsernamePasswordAuthenticationToken(username,password,authorities)
);

如果您已經知道它們已通過身份驗證,則無需使用AuthenticationManager 相反,您可以直接設置Authentication ,如下所示:

List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
Authentication authentication = new UsernamePasswordAuthenticationToken(username, null, authorities);
SecurityContextHolder.getContext().setAuthentication(authentication);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM