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 customize exception handling by SpringBoot Security

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

Share

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

This article mainly shows you "SpringBoot Security how to customize exception handling", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "SpringBoot Security how to customize exception handling" this article.

SpringBoot Security custom exception access_denied aspect exception

Original anomaly

{"error": "access_denied", "error_description": "access not allowed"}

Now abnormal

{"success": false, "error": "access_denied", "status": 403, "message": "No access", "path": "/ user/get1", "timestamp": 1592378892768}

Realize

Public class ResourceServerConfig extends ResourceServerConfigurerAdapter {@ Override public void configure (ResourceServerSecurityConfigurer resources) {/ / access_denied aspect exception OAuth3AccessDeniedHandler oAuth3AccessDeniedHandler = new OAuth3AccessDeniedHandler (); oAuth3AccessDeniedHandler.setExceptionTranslator (new CustomWebResponseExceptionTranslator ()); resources.accessDeniedHandler (oAuth3AccessDeniedHandler);}} Invalid access token aspect exception

Original anomaly

{"error": "invalid_token", "error_description": "Invalid access token: 4eb58ecf-e66de-4155-9477-64a1c9805cc8"}

Now abnormal

{"success": false, "error": "invalid_token", "status": 401, "message": "Invalid access token: 8cd45925dbf6-4502-bd13-8101bc6e1d4b", "path": "/ user/get1", "timestamp": 1592378949452}

Realize

Public class ResourceServerConfig extends ResourceServerConfigurerAdapter {@ Override public void configure (ResourceServerSecurityConfigurer resources) {/ / Invalid access token exception OAuth3AuthenticationEntryPoint authenticationEntryPoint = new OAuth3AuthenticationEntryPoint (); authenticationEntryPoint.setExceptionTranslator (new CustomWebResponseExceptionTranslator ()); resources.authenticationEntryPoint (authenticationEntryPoint);}} Bad credentials exception (login error)

Original anomaly

{"error": "invalid_grant", "error_description": "wrong username or password"}

Now abnormal

{"success": false, "error": "invalid_grant", "status": 400,400, "message": "user name or password error", "path": "/ oauth/token", "timestamp": 1592384576019}

Realize

Public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {@ Override public void configure (AuthorizationServerEndpointsConfigurer endpoints) {endpoints.userDetailsService (detailsService) .tokenStore (memoryTokenStore ()) .accountionTranslator (new CustomWebResponseExceptionTranslator ()) .authenticationManager (authenticationManager) / / receive GET and POST .allowedTokenEndpointReque stMethods (HttpMethod.GET, HttpMethod.POST) } other classes @ Getter@JsonSerialize (using = CustomOauthExceptionSerializer.class) public class CustomOauthException extends OAuth3Exception {private String oAuth3ErrorCode; private int httpErrorCode; public CustomOauthException (String msg, String oAuth3ErrorCode, int httpErrorCode) {super (msg); this.oAuth3ErrorCode = oAuth3ErrorCode; this.httpErrorCode = httpErrorCode;}} public class CustomOauthExceptionSerializer extends StdSerializer {private static final long serialVersionUID = 2652127645704345563L; public CustomOauthExceptionSerializer () {super (CustomOauthException.class) } @ Override public void serialize (CustomOauthException value, JsonGenerator gen, SerializerProvider provider) throws IOException {gen.writeStartObject (); HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes ()) .getRequest (); gen.writeObjectField ("success", false); gen.writeObjectField ("error", value.getOAuth3ErrorCode ()); gen.writeObjectField ("status", value.getHttpErrorCode ()); gen.writeObjectField ("message", value.getMessage ()) Gen.writeObjectField ("path", request.getServletPath ()); gen.writeObjectField ("timestamp", (new Date ()). GetTime ()); if (value.getAdditionalInformation ()! = null) {for (Map.Entry entry: value.getAdditionalInformation (). EntrySet ()) {String key = entry.getKey (); String add = entry.getValue () Gen.writeObjectField (key, add);}} gen.writeEndObject ();}} public class CustomWebResponseExceptionTranslator extends DefaultWebResponseExceptionTranslator {@ Override public ResponseEntity translate (Exception e) throws Exception {ResponseEntity translate = super.translate (e); OAuth3Exception body = translate.getBody (); CustomOauthException customOauthException = new CustomOauthException (body.getMessage (), body.getOAuth3ErrorCode (), body.getHttpErrorCode ()) ResponseEntity response = new ResponseEntity (customOauthException, translate.getHeaders (), translate.getStatusCode ()); return response;}} add {"error": "invalid_client", "error_description": "Bad client credentials"}

If the client_secret error is still reported as above, you need to add a filter in the addTokenEndpointAuthenticationFilter in the following method to deal with this exception.

@ Override public void configure (AuthorizationServerSecurityConfigurer oauthServer) {oauthServer / / Open / oauth/token_key authentication port does not have permission to access .tokenKeyAccess ("permitAll ()) / Open / oauth/check_token authentication port authentication permission access .che ckTokenAccess (" isAuthenticated () ") .addTokenEndpointauthenticationFilter (null) .allowFormauthenticationForClients () } SpringSecurity Custom response exception message

If the exception information is set here, there are still holes, for example, if you want to customize the token expiration information and invalid token, it will not take effect according to the SpringSecurity setting and need to be added to the resource configuration.

If it's just SpringSecurity, you only need to implement two interfaces, AccessDeniedHandler and AuthenticationEntryPoint. They all take effect in ExceptionTranslationFilter.

AuthenticationEntryPoint is used to resolve exceptions when anonymous users access unprivileged resources

RuAccessDeineHandler is used to resolve exceptions when authenticated users access unauthorized resources.

If you want to customize the expiration of token, you need to implement the AuthenticationEntryPoint interface, because the token expires, access is considered anonymous.

However, there is an order in the filter chain of SpringSecurity, and the OAuth3AuthenticationProcessingFilter of verifying token is in front of it, which leads to no way to take effect. All the resources need to be added to the configuration. Demo is as follows:

/ * * @ author WGR * @ create 2021-8-23-16:52 * / @ Componentpublic class SimpleAuthenticationEntryPoint implements AuthenticationEntryPoint {@ Override public void commence (HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws ServletException {Throwable cause = authException.getCause (); try {if (cause instanceof InvalidTokenException) {Map map = new HashMap () Map.put ("error", "invalid token"); map.put ("message", authException.getMessage ()); map.put ("path", request.getServletPath ()); map.put ("timestamp", String.valueOf (new Date (). GetTime (); response.setContentType ("application/json") Response.setStatus (HttpServletResponse.SC_UNAUTHORIZED); try {ObjectMapper mapper = new ObjectMapper (); mapper.writeValue (response.getOutputStream (), map);} catch (Exception e) {throw new ServletException () } catch (Exception e) {e.printStackTrace ();}

It can take effect. The returned information is as follows:

If you want to set custom exception information without permission:

/ * * @ author WGR * @ create 2021-8-23-17:09 * / @ Componentpublic class SimpleAccessDeniedHandler implements AccessDeniedHandler {@ Override public void handle (HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {Map map = new HashMap (); map.put ("message", "unauthorized operation"); map.put ("path", request.getServletPath ()) Map.put ("timestamp", String.valueOf (new Date (). GetTime ()); response.setContentType ("application/json"); response.setStatus (HttpServletResponse.SC_FORBIDDEN); try {ObjectMapper mapper = new ObjectMapper (); mapper.writeValue (response.getOutputStream (), map);} catch (Exception e) {throw new ServletException ();}

Set it to springsecurity and add it. If you don't want to capture the expiration of token, you can add it directly.

The above is all the content of the article "how to customize exception handling by SpringBoot Security". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

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