【发布时间】:2018-11-08 19:05:31
【问题描述】:
对不起,我的英语。
我有一个应用程序,我可以用通常的方式登录。
@Configuration
@EnableWebSecurity
public class LoginSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
System.out.println("LoginSecurityConfig :: configure");
auth.jdbcAuthentication().dataSource( getDataSource() )
.passwordEncoder( new BCryptPasswordEncoder(16) )
.usersByUsernameQuery(
"select user_name as username,password,enabled from users where user_name=?")
.authoritiesByUsernameQuery(
"select user_name as username, role_name from users_roles ur join users u on ur.user_id = u.user_id and u.user_name = ?");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/login*").anonymous()
.antMatchers("/resources/**").permitAll()
.antMatchers("/fotos/**").permitAll()
.antMatchers("/users").access("hasRole('ROLE_ADMIN')")
.antMatchers("/user").access("hasRole('ROLE_ADMIN')")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/loginPage")
.defaultSuccessUrl("/home", true)
.failureUrl("/loginPage?error=true")
.loginProcessingUrl("/login")
.usernameParameter("username")
.passwordParameter("password")
.and()
.logout()
.logoutSuccessUrl("/loginPage")
.invalidateHttpSession(true);
}
}
使用这个我可以尝试访问任何安全资源,系统将我发送到loginPage,我可以将username和password发布到内部login控制器然后我有Principal并且可以访问受保护的资源(家庭、用户、用户)。工作正常。
但是...我需要删除用户控制数据库的内容并使用 OAuth2 来允许相同类型的访问。我不想再在我的数据库中有任何用户了。我需要一个登录屏幕,然后是像http://myserver/oauth/token?grant_type=password&username=admin&password=admin 这样的令牌请求,在Basic 中传递client_id 和client_secret。我知道如何执行“获取令牌”部分,并且我的服务器工作正常并给我令牌和刷新令牌,但只使用 Postman,因为我不知道如何在我的 Web 应用程序代码中使用它。我发现的所有教程都在同一个应用程序中同时使用服务器和客户端,实际上并没有展示如何使用 OAuth2 远程服务器。
已经尝试使用this。这是一个很好的教程,非常接近我的需要,但对我来说太复杂了。
我有这段代码并且理解它可以使用服务器并使用客户端凭据发出令牌,但不知道如何为用户提供登录屏幕并获取他的凭据以完成请求(GET部分)。
@Configuration
@EnableResourceServer
public class OAuth2ResourceServerConfigRemoteTokenService extends ResourceServerConfigurerAdapter {
@Override
public void configure(final HttpSecurity http) throws Exception {
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.and()
.authorizeRequests().anyRequest().permitAll();
}
@Primary
@Bean
public RemoteTokenServices tokenServices() {
final RemoteTokenServices tokenService = new RemoteTokenServices();
tokenService.setCheckTokenEndpointUrl("http://myoauthserver/oauth/check_token");
tokenService.setClientId("clientid");
tokenService.setClientSecret("password");
return tokenService;
}
}
所以...如何保护我的系统,从用户那里获取登录名和密码,并使用此代码来控制凭据,就像我使用通常的数据库方法一样?
或者 OAuth2 仅用于安全的 REST API?
请对新手友好,因为我不太习惯使用 Spring。
【问题讨论】:
标签: spring-mvc spring-security-oauth2