Browse Source

fix:oauth2 匿名用户

liujunchi 3 years ago
parent
commit
7fb5fbd694

+ 28 - 0
cooleshow-user/user-website/src/main/java/com/yonge/cooleshow/website/config/MyOAuth2AuthenticationManager.java

@@ -0,0 +1,28 @@
+package com.yonge.cooleshow.website.config;
+
+import org.springframework.security.authentication.AnonymousAuthenticationToken;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.core.authority.AuthorityUtils;
+import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
+import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationManager;
+
+import java.util.UUID;
+
+/**
+ * Description
+ *
+ * @author liujunchi
+ * @date 2022-06-30
+ */
+public class MyOAuth2AuthenticationManager extends OAuth2AuthenticationManager {
+
+    @Override
+    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
+        try {
+            return super.authenticate(authentication);
+        } catch (AuthenticationException | InvalidTokenException e) {
+            return new AnonymousAuthenticationToken(UUID.randomUUID().toString(), "anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
+        }
+    }
+}

+ 1 - 0
cooleshow-user/user-website/src/main/java/com/yonge/cooleshow/website/config/ResourceServerConfig.java

@@ -39,6 +39,7 @@ public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
     @Override
     public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
         resources.authenticationEntryPoint(baseAuthenticationEntryPoint).accessDeniedHandler(baseAccessDeniedHandler);
+        resources.authenticationManager(new MyOAuth2AuthenticationManager());
     }
 
 }