How to create Custom UserDetail Object in Spring Security

前端 未结 3 985
春和景丽
春和景丽 2020-12-16 21:06

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

   public class AccountAuthenticationProvider implements  Aut         


        
3条回答
  •  無奈伤痛
    2020-12-16 21:56

    You almost had it!

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

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

    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, UserDetails and UserDetailsService to help manage users and do Springy stuff with users, so if you make MyObject implement UserDetails then you can get a few extra benefits from the Spring environment, but it is not necessary you can stick with just your MyObject.

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

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

提交回复
热议问题