Я создал сервер авторизации OAuth с использованием конфигураций весенней загрузки по умолчанию, где клиент перенаправляется на автоматически сгенерированную страницу входа, userDetailsService ищет таблицу User и выполняет аутентификацию, а после успешной аутентификации сервер возвращает токен jwt. Теперь я хочу настроить это и изменить две вещи, но мне трудно это делать.
1) Используйте мою собственную страницу login.jsp вместо автоматически сгенерированной страницы входа, чтобы я мог иметь дополнительное поле (например, dropdownlist) и использовать его вместе с именем пользователя и паролем для аутентификации, так как у меня разныепользовательские таблицы
2) Вместо использования UserDetailsService по умолчанию я пытаюсь реализовать свой собственный AuthenticationProvider, это потому, что у меня есть таблица из нескольких пользователей, и я хочу найти пользователя в правильной таблице на основе значения из дополнительногополе (раскрывающийся список упоминается в 1). Также как получить значение раскрывающегося списка в AuthenticationProvider?
В моем файле свойств я установил: spring.mvc.view.prefix: / WEB-INF / jsp / и spring.mvc.view.suffix: .jsp
@Configuration
@EnableWebSecurity
public class ServerWebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Autowired
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(new DefaultAuthenticationProvider());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.requestMatchers()
.antMatchers("/login", "/oauth/authorize")
.and()
.authorizeRequests()
.anyRequest().authenticated();
}
}
@Configuration
@EnableAuthorizationServer
@Import(ServerWebSecurityConfig.class)
public class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter{
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
@Qualifier("dataSource")
private DataSource dataSource;
@Autowired
private UserDetailsService userDetailsService;
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore()).accessTokenConverter(accessTokenConverter()).authenticationManager(authenticationManager);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("permitAll()");
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
JdbcClientDetailsService jdbcClientDetailsService = new JdbcClientDetailsService(dataSource);
clients.withClientDetails(jdbcClientDetailsService);
}
@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(accessTokenConverter());
}
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey("secret");
return converter;
}
@Bean
@Primary
public DefaultTokenServices tokenServices() {
DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
defaultTokenServices.setTokenStore(tokenStore());
defaultTokenServices.setSupportRefreshToken(true);
return defaultTokenServices;
}
@Bean
public PasswordEncoder userPasswordEncoder() {
return new BCryptPasswordEncoder();
}
}
public class DefaultAuthenticationProvider implements AuthenticationProvider {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
if (authentication.getName() == null || authentication.getCredentials() == null
|| authentication.getName().isEmpty() || authentication.getCredentials().toString().isEmpty()) {
return null;
}
final String userName = authentication.getName();
final String password = (String) authentication.getCredentials();
// final String userTable = how to get this?
// make db query in correct table based on value of userTable
User user = null;
Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
for (UserAuthority authority : user.getUserAuthorities()) {
authorities.add(new CustomGrantedAuthority(authority.getAuthority().getName()));
}
Map<String, String> userDetails = new HashMap<>();
userDetails.put("username", userName);
return new UsernamePasswordAuthenticationToken(userDetails, password, authorities);
}
@Override
public boolean supports(Class<?> authentication) {
return false;
}
}
@Controller
public class OAuthController {
@RequestMapping("/login")
public String login() {
return "login";
}
}
I am expecting that my client app is redirected to the custom login page, once login button is pressed my custom AuthenticationProvider will lookup for user in the correct table based on the extra field in the custom login page.