Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand Spring Boot authentication and authentication

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "how to understand Spring Boot authentication and authentication". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

In web applications, there are a large number of scenarios where users need to be securely calibrated. What most people do is to bury the hard code directly into the business code, but have you ever thought that this will lead to code not concise enough (a lot of repeated code), difficult to maintain when personalized (each business logic access control policy is different or even very different), and prone to security leaks (some businesses may not require current login information). However, the accessed data may be sensitive data that is not protected due to forgetting.

For more secure and convenient access security control, we can think of using springmvc's interceptor (HandlerInterceptor), but in fact, it is recommended to use a more mature spring security for authentication and authentication.

Interceptor

Interceptor HandlerInterceptor can really help us to accomplish the requirements of login interception, or permission verification, or anti-duplicate submission. In fact, security control based on url or method level can also be realized based on it.

If you have a relative understanding of spring mvc's request processing process, its principle is easy to understand, please refer to my previous sharing.

Public interface HandlerInterceptor {/ * * Intercept the execution of a handler. Called after HandlerMapping determined * an appropriate handler object, but before HandlerAdapter invokes the handler. * * called before the business processor processes the request. Pre-processing, you can perform coding, security control, permission verification and other processing methods in * * handler:controller. You can obtain @ RequestMapping * / boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception; / * Intercept the execution of a handler through HandlerMethod method= ((HandlerMethod) handler). Called after HandlerAdapter actually * invoked the handler, but before the DispatcherServlet renders the view. * * execute after the request is processed by the business processor and before the view is generated. Post-processing (Service is called and ModelAndView is returned, but the page is not rendered). There is a chance to modify ModelAndView * / void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception; / * Callback after completion of request processing, that is, after rendering * the view. Will be called on any outcome of handler execution, thus allows * for proper resource cleanup. * * it is called after the DispatcherServlet has fully processed the request, and can be used to clean up resources, etc. Return processing (page has been rendered) * * / void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception;} / / you can intercept @ Configurationpublic class UserSecurityInterceptor extends WebMvcConfigurerAdapter {@ Override public void addInterceptors (InterceptorRegistry registry) {String [] securityUrls = new String [] {"/ *"} based on some url String [] excludeUrls = new String [] {"/ * * / esb/**", "/ * * / dictionary/**"}; registry.addInterceptor (userLoginInterceptor ()) .origindePathPatterns (excludeUrls) .addPathPatterns (securityUrls); super.addInterceptors (registry);} / * * fixed: url contains / / error report * org.springframework.security.web.firewall.RequestRejectedException: The request was rejected because the URL was not normalized. * @ return * / @ Bean public HttpFirewall allowUrlEncodedSlashHttpFirewall () {DefaultHttpFirewall firewall = new DefaultHttpFirewall (); firewall.setAllowUrlEncodedSlash (true); return firewall;} @ Bean public AuthInterceptor userLoginInterceptor () {return new AuthInterceptor ();} public class AuthInterceptor implements HandlerInterceptor {public Logger logger = LoggerFactory.getLogger (AuthInterceptor.class); @ Autowired private ApplicationContext applicationContext Public AuthInterceptor () {} @ Override public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {LoginUserInfo user = null; try {user = (LoginUserInfo) SSOUserUtils.getCurrentLoginUser ();} catch (Exception e) {logger.error ("failed to get user information from SSO login information! Detailed error message:% s ", e); throw new ServletException (" failed to get user information from SSO login information! " , e);} String [] profiles = applicationContext.getEnvironment (). GetActiveProfiles (); if (! Arrays.isNullOrEmpty (profiles)) {if ("dev" .equals (profiles [0])) {return true }} if (user = = null | | UserUtils.ANONYMOUS_ROLE_ID.equals (user.getRoleId () {throw new ServletException ("failed to get login user information!") ;} return true;} @ Override public void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {} @ Override public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {}} certification

Identify who is the user behind an access request and what his user information looks like. There are many ways to authenticate in spring security, the simplest of which is user name and password, as well as LDAP, OpenID, CAS and so on.

In our system, user information needs to be obtained through the kxtx-sso module. It is relatively simple to pass sso authentication, that is, to confirm whether the user is logged in through the member system, and to package the login information as an authorized object and put it into the SecurityContext, which can be done through a filter:

@ Data@EqualsAndHashCode (callSuper = false) public class SsoAuthentication extends AbstractAuthenticationToken {private static final long serialVersionUID =-1799455508626725119L; private LoginUserInfo user; public SsoAuthentication (LoginUserInfo user) {super (null); this.user = user;} @ Override public Object getCredentials () {return "kxsso";} @ Override public Object getPrincipal () {return user } @ Override public String getName () {return user.getName ();}} public class SsoAuthenticationProcessingFilter extends OncePerRequestFilter {@ Override protected void doFilterInternal (HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {LoginUserInfo user = (LoginUserInfo) SSOUserUtils.getCurrentLoginUser (); SsoAuthentication auth = new SsoAuthentication (user); SecurityContextHolder.getContext () .setAuthentication (auth); filterChain.doFilter (request, response) } @ Componentpublic class SsoAuthenticationProvider implements AuthenticationProvider {@ Value ("${env}") String env; @ Override public Authentication authenticate (Authentication authentication) throws AuthenticationException {LoginUserInfo loginUserInfo = (LoginUserInfo) authentication.getPrincipal (); / * * the DEV environment allows anonymous users to access to facilitate debugging. Other environments must be logged in. * / if (! UserUtils.ANONYMOUS_ROLE_ID.equals (loginUserInfo.getRoleId ()) | | "dev" .equals (env)) {authentication.setAuthenticated (true);} else {throw new BadCredentialsException ("login");} return authentication;} @ Override public boolean supports (Class authentication) {return SsoAuthentication.class.equals (authentication) } @ Configuration@EnableWebSecurity@EnableGlobalMethodSecurity (securedEnabled = true, prePostEnabled = true) public class WebSecurityConfig extends WebSecurityConfigurerAdapter {protected void configure (HttpSecurity http) throws Exception {/ / close session http.sessionManagement (). SessionCreationPolicy (SessionCreationPolicy.STATELESS). And (); / / allow access to all URL, restricting access through method protection. Http.authorizeRequests () .anyRequest () .permitAll (); / register sso filter http.addFilterBefore (ssoAuthenticationProcessingFilter (), UsernamePasswordAuthenticationFilter.class);} @ Bean SsoAuthenticationProcessingFilter ssoAuthenticationProcessingFilter () {return new SsoAuthenticationProcessingFilter ();}} Authentication

Controls whether a function can be accessed by the current user and rejects users who do not meet the requirements. There are two main types of control points for spring security:

Based on the request path: controlling a certain URL pattern must meet certain requirements

Method-based: controlling a method must meet certain requirements

The forms of control are more diversified:

Code configuration

Xml configuration

Annotation control

El expression

Custom access controller

At present, the requirement of authentication is relatively simple: login allows access, non-login forbids access. Therefore, a section can be defined to control all Controller that require security control.

Spring security provides some notes:

@ PreAuthorize

Controls whether a method can be called, the preprocessing of a business method (HandlerMethod), such as:

@ PreAuthorize ("# id

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report