In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces the "Spring Security single sign-on permission function how to use" related knowledge, editor through the actual case to show you the operation process, the operation method is simple and fast, practical, I hope that this "Spring Security single sign-on permission function how to use" article can help you solve the problem.
Background
Add permissions to the configuration center
At present, the configuration center already includes a single sign-on function. You can log in through the unified page. After logging in, the user will be written to the user table.
The user, role, permission table CRUD, authorization and so on of RBAC have been completed.
It is hoped that without the user logging in again, the permission control of SpringSecurity can be used.
Spring Security
Two main functions of Spring Security: authentication and authorization
The problem of functional solution in Spring Security main Class Authentication (Authentication) who are you AuthenticationManager Authorization (Authorization) what can you do AuthorizationManager implementation
Let's take a brief look at the architecture of Spring Security and how it can be authenticated and authorized.
Filters you should know that this belongs to the category of Servlet. Servlet filters can dynamically intercept requests and responses to transform or use the information contained in the request or response.
DelegatingFilterProxy is a filter belonging to Spring Security
Through this filter, Spring Security can obtain URL from Request to determine whether authentication is required to access it, and whether it needs to have specific permissions to access it.
You already have a single sign-on page. How do you log in with Spring Security? can you get permission if you don't log in?
Spring Security official documentation-the authorization architecture says that GrantedAuthority (that is, permissions) is written to the Authentication object by AuthenticationManager and then used by AuthorizationManager to authenticate permissions.
The GrantedAuthority objects are inserted into the Authentication object by the AuthenticationManager and are later read by either the AuthorizationManager when making authorization decisions.
In order to solve our problem, even if I only want to use the authorization feature, I have to create an Authentication. Take a look at this object first:
Authentication
Authentication contains three fields:
Principal, representing the user
Credentials, user password
Authorities, the permissions you have
It has two functions:
The input parameter of AuthenticationManager is only used to store the user's information and prepare to authenticate.
The output parameter of AuthenticationManager and the authenticated user information can be obtained from SecurityContext.
SecurityContext and SecurityContextHolder are used to store Authentication, usually using the thread global variable ThreadLocal, that is, when the authentication is completed, the Authentication is put into the SecurityContext, and the authentication information can be obtained in the whole process of the same thread, which also facilitates the authentication.
Continue to analyze
See that this can be obtained, in order to achieve non-login permission authentication, just manually create an Authentication, and then put in the SecurityContext, try it first, roughly the process is like this, on each request
Get the user logged in to sso
Read user, role, permission to write to Authentication
Write Authentication to SecurityContext
Empty the SecurityContext when the request is completed, because it belongs to ThreadLocal, otherwise it may be used by other users.
At the same time, the configuration of Spring Security allows access to all url.
Add a filter, the code is as follows:
Import javax.servlet.*;import javax.servlet.annotation.WebFilter;import javax.servlet.http.HttpServletRequest;import java.io.IOException;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.stream.Collectors;@WebFilter (urlPatterns = "/ *", filterName = "reqResFilter") public class ReqResFilter implements Filter {@ Autowired private SSOUtils ssoUtils; @ Autowired private UserManager userManager; @ Autowired private RoleManager roleManager @ Override public void init (FilterConfig filterConfig) throws ServletException {} @ Override public void doFilter (ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {setAuthentication (servletRequest); filterChain.doFilter (servletRequest, servletResponse); clearAuthentication () } @ Override public void destroy () {} private void setAuthentication (ServletRequest request) {Map data; try {data = ssoUtils.getLoginData ((HttpServletRequest) request);} catch (Exception e) {data = new HashMap () Data.put ("name", "visitor");} String username = data.get ("name"); if (username! = null) {userManager.findAndInsert (username);} List userRole = userManager.findUserRole (username) List roleIds = userRole.stream (). Map (Role::getId). Collect (Collectors.toList ()); List rolePermission = roleManager.findRolePermission (roleIds); List authorities = rolePermission.stream (). Map (one-> new SimpleGrantedAuthority (one.getName ())). Collect (Collectors.toList ()) UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken (username, ", authorities); SecurityContextHolder.getContext () .setAuthentication (authenticationToken);} private void clearAuthentication () {SecurityContextHolder.clearContext ();}}
As you can see from the log, Principal: visitor, when access to an unauthorized interface is denied
16 http-nio-8081-exec-9 04VR 07.429 [http-nio-8081-exec-9] DEBUG org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor-Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@cc4c6ea0: Principal: visitor; Credentials: [PROTECTED]; Authenticated: true; Details: null; Granted Authorities: CHANGE_USER_ROLE, CHANGE_ROLE_PERMISSION, ROLE_ADD...org.springframework.security.access.AccessDeniedException: access to conclusion is not allowed
If you do not log in, you can use the permission of Spring Security. There is no problem in terms of function, but there are some other problems.
Performance problems, each request needs to request user role permissions to the database, of course, you can use cache optimization
The filter we wrote is actually what Spring Security does, and in addition, it does more things, such as combining HttpSession and Remember me functions.
We can take another approach, for users to log in only once, we can still use the code to log in to Spring Security again.
How to log in to Spring Security manually
How to login user from java code in Spring Security? As you can see from this article, you only need to use the following code
Private void loginInSpringSecurity (String username, String password) {UsernamePasswordAuthenticationToken loginToken = new UsernamePasswordAuthenticationToken (username, password); Authentication authenticatedUser = authenticationManager.authenticate (loginToken); SecurityContextHolder.getContext (). SetAuthentication (authenticatedUser);}
Compared directly with the authenticated users above, this code allows Spring Security to perform the authentication steps, but additional AuthenticationManager and UserDetailsServiceImpl need to be configured. These two configurations are only an implementation of AuthenticationManager, not much different from the above process. The purpose is to get the user's information and permissions for authentication.
Import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.security.core.GrantedAuthority;import org.springframework.security.core.authority.SimpleGrantedAuthority;import org.springframework.security.core.userdetails.UserDetails;import org.springframework.security.core.userdetails.UserDetailsService;import org.springframework.security.core.userdetails.UsernameNotFoundException;import org.springframework.stereotype.Service;import java.util.List;import java.util.stream.Collectors @ Servicepublic class UserDetailsServiceImpl implements UserDetailsService {private static final Logger logger = LoggerFactory.getLogger (UserDetailsServiceImpl.class); @ Autowired private UserManager userManager; @ Autowired private RoleManager roleManager; @ Override public UserDetails loadUserByUsername (String username) throws UsernameNotFoundException {User user = userManager.findByName (username) If (user = = null) {logger.info ("logged in user [{}] not registered!", username); throw new UsernameNotFoundException ("logged in user [" + username + "] not registered!") } return new org.springframework.security.core.userdetails.User (user.getUsername (), ", getAuthority (username));} private List
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.