Browse Source

匿名访问

刘俊驰 1 năm trước cách đây
mục cha
commit
a1365b8974

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

@@ -0,0 +1,28 @@
+package com.yonge.cooleshow.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"));
+        }
+    }
+}

+ 6 - 4
cooleshow-app/src/main/java/com/yonge/cooleshow/config/ResourceServerConfig.java

@@ -53,9 +53,11 @@ public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
 				.and().httpBasic();
 	}
 
-	@Override
-	public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
-		resources.authenticationEntryPoint(baseAuthenticationEntryPoint).accessDeniedHandler(baseAccessDeniedHandler);
-	}
+
+    @Override
+    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
+        resources.authenticationEntryPoint(baseAuthenticationEntryPoint).accessDeniedHandler(baseAccessDeniedHandler);
+        resources.authenticationManager(new MyOAuth2AuthenticationManager());
+    }
 
 }