我正在使用以下配置通过 oauth 和常规授权来实现授权。
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests().mvcMatchers("/robots.txt").permitAll()
.antMatchers(
"/", "/auth", "/signup", "/restore", "/activation/**",
"/admin/login", "/admin_restore",
"/agreement", "/privacy", "/about-us", "/faq", "/contact-us",
"/error",
"/page/**", "/categories", "/categories/**"
).permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/auth")
.loginProcessingUrl("/auth")
.usernameParameter("email")
.passwordParameter("password")
.defaultSuccessUrl("/")
.failureUrl("/auth?authError")
.permitAll()
.and()
.rememberMe()
.rememberMeParameter("remember-me")
.tokenValiditySeconds(86400)
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/")
.deleteCookies("JSESSIONID")
.and()
.oauth2Login().defaultSuccessUrl("/oauth")
.and()
.exceptionHandling()
.accessDeniedPage("/403")
.and()
.csrf()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.ALWAYS)
.and()
.headers().frameOptions().sameOrigin();
}
原则上,授权可以正常工作。但!我还需要在授权用户时确定他的授权日期和时间。我已经实现了常规授权的工作功能,但是 OAuth2 授权存在问题。
@Service
public class UserService implements
ApplicationListener<AuthenticationSuccessEvent> {
/**
Переопределяем метод onApplicationEvent(), чтобы при авторизации юзера зафиксировать дату и время его авторизации
*/
@Override
public void onApplicationEvent(AuthenticationSuccessEvent event) {
>>> Ex.here! String userEmail = ((UserDetails) event.getAuthentication().
getPrincipal()).getUsername();
User user = this.userRepository.findByUserEmail(userEmail);
user.setLastAuthDate(LocalDateTime.now());
userRepository.save(user);
}
...
}
如果通过oauth登录,则会出现以下异常:
java.lang.ClassCastException: org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser cannot be cast to org.springframework.security.core.userdetails.UserDetails
因此,问题是 - 如何消除此异常,以便 oauth 用户在进入站点时的授权也是固定的?如何区分普通用户和 oauth 授权用户?我有一个问题......
预先感谢您的帮助!
一般来说,多亏了关于检查授权类型的提示,我解决了这个问题。我不知道执行任务的结果如何,但代码正在运行。
我们捕获 AuthenticationSuccessEvent 并查看它的类型。基本授权 - UsernamePasswordAuthenticationToken OAuth2 授权 - OAuth2LoginAuthenticationToken
进一步,如果正常授权,那么我们在数据库中查找用户并修复当前授权时间。如果 oauth2 授权,如果这个用户不在数据库中,那么我们创建它,如果这个用户存在,那么我们找到它并修复最后一次授权的时间。