when loadUserByUsername is invoked? (spring security)

筅森魡賤 提交于 2020-11-30 09:34:06

问题


I'm learning Spring Security and I have few quick questions respect UserDetailsService:

1- When loadUserByUsername is actually called or invoked? After authentication? Only once per login?

2- After login, will Spring put the actual logged user into httpSession?

3- Which is the recommended way to populate the collection of <GrantedAuthority> of UserDetails?

  1. Eagle fetch them so when loadUserByUsername is called, the returned user already has it's "ROLES"
  2. Implement another custom filter like UsernamePasswordAuthenticationFilter populate after success login?
  3. Neither of above…

回答1:


  1. It is typically called by an AuthenticationProvider instance in order to authenticate a user. For example, when a username and password is submitted, a UserdetailsService is called to find the password for that user to see if it is correct. It will also typically provide some other information about the user, such as the authorities and any custom fields you may want to access for a logged in user (email, for instance). That is the main usage pattern. You can grep the code to see exactly where it is called.

As explained in the manual:

There is often some confusion about UserDetailsService. It is purely a DAO for user data and performs no other function other than to supply that data to other components within the framework. In particular, it does not authenticate the user, which is done by the AuthenticationManager. In many cases it makes more sense to implement AuthenticationProvider directly if you require a custom authentication process.

  1. Yes. A SecurityContext instance is stored in the session once the user has been authenticated.

  2. If you need to implement a custom UserDetailsService then it will depend on your requirements and how they are stored. Typically you would load them at the same time as the other user information. It's not something you would likely do in a filter. As explained in the above quotation from the manual, if you are actually implementing a different authentication mechanism then you should implement AuthenticationProvider directly. It isn't compulsory to have a UserDetailsService in your app. You can think of it as a strategy that is used by certain built-in features.



来源:https://stackoverflow.com/questions/10852703/when-loaduserbyusername-is-invoked-spring-security

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!