Java 如何在 Spring Security 中创建自定义 UserDetail 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26447739/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 02:30:52  来源:igfitidea点击:

How to create Custom UserDetail Object in Spring Security

javaspringspring-mvcspring-security

提问by user962206

I have built my custom Authenticaton Manager for Spring Security which goes something like this

我已经为 Spring Security 构建了我的自定义身份验证管理器,它是这样的

   public class AccountAuthenticationProvider implements  AuthenticationProvider{

    @Autowired
    private AuthenticationService authService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

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

        if(authService.isValid(userName,password)){
            List<GrantedAuthority> grantedAuthorityList = new ArrayList<GrantedAuthority>();
            grantedAuthorityList.add(new SimpleGrantedAuthority("ROLE_USER"));
            SecurityContext securityContext = new SecurityContextImpl();
            return  new UsernamePasswordAuthenticationToken(userName,password);
        }

        return null;
    }


    public void setAuthService(AuthenticationService authService) {
        this.authService = authService;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }

}

but how do I create my own custom UserDetail object? I'll use that to store account related values

但是如何创建自己的自定义 UserDetail 对象?我将使用它来存储与帐户相关的值

回答by Bassem Reda Zohdy

you need to implement UserDetailsService and override loadUserByUsername method to return your customized UserDetails class.

您需要实现 UserDetailsS​​ervice 并覆盖 loadUserByUsername 方法以返回您自定义的 UserDetails 类。

check below links:

检查以下链接:

http://www.javaroots.com/2013/03/how-to-use-custom-dao-classe-in-spring.htmlhttp://www.javacodegeeks.com/2012/08/spring-security-implementing-custom.html

http://www.javaroots.com/2013/03/how-to-use-custom-dao-classe-in-spring.html http://www.javacodegeeks.com/2012/08/spring-security-implementing -custom.html

回答by Sudhir Khatri

you need to implement UserDetailsService and override loadUserByUsername method to return your customized UserDetails class. Like this-

您需要实现 UserDetailsS​​ervice 并覆盖 loadUserByUsername 方法以返回您自定义的 UserDetails 类。像这样-

public class UserServiceImpl implements UserDetailsService {`

@Autowired
UserDaoImpl userDao;

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    System.out.println(username);
    Users user = (Users) userDao.findByUserName(username);
    List<GrantedAuthority> authorities = buildUserAuthority(user.getUserRoles());
    System.out.println("after....");
    return buildUserForAuthentication(user, authorities);
}

private List<GrantedAuthority> buildUserAuthority(Set<UserRole> userRoles) {
    Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>(); 
    for(UserRole userRole  : userRoles){
        System.out.println("called buildUserAuthority(Set<UserRole> userRoles) method.....");
        setAuths.add(new SimpleGrantedAuthority(userRole.getRole()));
    }

    List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(setAuths);
    return grantedAuthorities;
}

private User buildUserForAuthentication(Users user, List<GrantedAuthority> authorities) {
    //accountNonExpired, credentialsNonExpired, accountNonLocked, authorities properties
    System.out.println("called buildUserForAuthentication(Users user, List<GrantedAuthority> authorities) method....");
    return new User(user.getUsername(), user.getPassword(), user.getEnabled(), true, true, true, authorities);
}}

回答by David Newcomb

You almost had it!

你几乎拥有它!

if(authService.isValid(userName,password)) {
    List<GrantedAuthority> grantedAuthorityList = new ArrayList<GrantedAuthority>();
    grantedAuthorityList.add(new SimpleGrantedAuthority("ROLE_USER"));
    MyObject myObj = new MyObject(userName, password, otherInfo);
    return  new UsernamePasswordAuthenticationToken(mjObj,"", grantedAuthorityList);
}

The first argument to UsernamePasswordAuthenticationTokenis the principle. The principle is the object in the system that represents the person (or thing) that just logged in.

第一个论点UsernamePasswordAuthenticationToken是原则。原则是系统中代表刚刚登录的人(或物)的对象。

Before authentication the principle is just the (String) username because that's all the information you have at that point. After logging in you may collect other information to go with the user.

在身份验证之前,原则只是(字符串)用户名,因为这是您当时拥有的所有信息。登录后,您可能会收集其他信息以与用户一起使用。

Spring offers interfaces: User, UserDetailsand UserDetailsServiceto help manage users and do Springy stuff with users, so if you make MyObjectimplement UserDetailsthen you can get a few extra benefits from the Spring environment, but it is not necessary you can stick with just your MyObject.

Spring 提供了接口:User,UserDetailsUserDetailsService帮助管理用户和与用户一起做一些 Springy 的事情,所以如果你MyObject实现了,UserDetails那么你可以从 Spring 环境中获得一些额外的好处,但是你没有必要只坚持你的MyObject.

In your controllers (in Spring 4) you can use the @AuthenticationPrincipalto inject the user object into the calls, e.g.:

在您的控制器中(在 Spring 4 中),您可以使用@AuthenticationPrincipal将用户对象注入到调用中,例如:

@RequestMapping(method = RequestMethod.GET, value = "/foo/{bar}")
public SomeObject myCommand(@AuthenticationPrincipal MyObject user, @PathVariable String bar);