Example Analysis of Spring Security Architecture and Source Code
This article is about the Spring Security architecture and the sample analysis of the source code. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
Preface
Now the popular general authorization framework is apache's shiro and Spring family's Spring Security. When it comes to today's micro-service authentication, we need to use our authorization framework to build our own authentication service. Today, Prime Minister Spring Security.
Spring Security mainly implements Authentication (authentication, solving who are you?) and Access Control (access control, that is, what are you allowed to do? Also known as Authorization) Spring Security architecturally separates authentication from authorization and provides extension points.
Core object
The main code is under the spring-security-core package. To understand Spring Security, you need to focus on the core objects in it.
SecurityContextHolder, SecurityContext and Authentication
SecurityContextHolder is the storage container for SecurityContext, and ThreadLocal storage is used by default, which means that all methods of SecurityContext in the same thread are available.
SecurityContext is mainly used to store the principal information of the application, which is represented by Authentication in Spring Security.
Get principal:
Object principal = SecurityContextHolder.getContext (). GetAuthentication (). GetPrincipal (); if (principal instanceof UserDetails) {String username = ((UserDetails) principal). GetUsername ();} else {String username = principal.toString ();}
In Spring Security, you can look at the Authentication definition:
Public interface Authentication extends Principal, Serializable {Collection