@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
@Bean
protected AuthorizationCodeServices authorizationCodeServices() {
return new CustomJdbcAuthorizationCodeServices(dataSource());
}
}
public class CustomJdbcAuthorizationCodeServices extends JdbcAuthorizationCodeServices {
private RandomValueStringGenerator generator = new RandomValueStringGenerator();
public CustomJdbcAuthorizationCodeServices(DataSource dataSource) {
super(dataSource);
this.generator = new RandomValueStringGenerator(32);
}
public String createAuthorizationCode(OAuth2Authentication authentication) {
String code = this.generator.generate();
store(code, authentication);
return code;
}
}
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
@Bean
public TokenEnhancer tokenEnhancer() {
return new CustomTokenEnhancer();
}
}
public class CustomTokenEnhancer implements TokenEnhancer {
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
if (accessToken instanceof DefaultOAuth2AccessToken) {
DefaultOAuth2AccessToken token = ((DefaultOAuth2AccessToken) accessToken);
token.setValue(getNewToken());
OAuth2RefreshToken refreshToken = token.getRefreshToken();
if (refreshToken instanceof DefaultOAuth2RefreshToken) {
token.setRefreshToken(new DefaultOAuth2RefreshToken(getNewToken()));
}
Map additionalInformation = new HashMap();
additionalInformation.put("client_id", authentication.getOAuth2Request().getClientId());
token.setAdditionalInformation(additionalInformation);
return token;
}
return accessToken;
}
private String getNewToken() {
return UUID.randomUUID().toString().replace("-", "");
}
}
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthorizationEndpoint authorizationEndpoint;
@PostConstruct
public void init() {
authorizationEndpoint.setUserApprovalPage("forward:/oauth/my_approval_page");
authorizationEndpoint.setErrorPage("forward:/oauth/my_error_page");
}
}
@Controller
@SessionAttributes({ "authorizationRequest" })
public class OAuthController {
@RequestMapping({ "/oauth/my_approval_page" })
public String getAccessConfirmation(Map model, HttpServletRequest request) throws Exception {
@SuppressWarnings("unchecked")
Map scopes = (Map) (model.containsKey("scopes") ? model.get("scopes") : request.getAttribute("scopes"));
List scopeList = new ArrayList();
for (String scope : scopes.keySet()) {
scopeList.add(scope);
}
model.put("scopeList", scopeList);
return "oauth_approval";
}
@RequestMapping({ "/oauth/my_error_page" })
public String handleError(Map model, HttpServletRequest request) {
Object error = request.getAttribute("error");
String errorSummary;
if (error instanceof OAuth2Exception) {
OAuth2Exception oauthError = (OAuth2Exception) error;
errorSummary = HtmlUtils.htmlEscape(oauthError.getSummary());
} else {
errorSummary = "Unknown error";
}
model.put("errorSummary", errorSummary);
return "oauth_error";
}
}
xmlns:th="http://www.thymeleaf.org">
approval
授权页
应用名 : clientId
xmlns:th="http://www.thymeleaf.org">
error
错误
出错了!不能继续授权操作!
errorSummary
CREATE TABLE account
(
id serial NOT NULL,
user_name character varying(50),
email character varying(255),
password character varying(512),
role_string character varying(50),
CONSTRAINT account_pkey PRIMARY KEY (id)
);
INSERT INTO account(user_name, email, password, role_string)
VALUES ('user', '[email protected]', '123', 'ROLE_USER');
@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
@EnableWebSecurity
static class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.antMatcher("/oauth/**")
.authorizeRequests()
.antMatchers("/oauth/index").permitAll()
.antMatchers("/oauth/token").permitAll()
.antMatchers("/oauth/check_token").permitAll()
.antMatchers("/oauth/confirm_access").permitAll()
.antMatchers("/oauth/error").permitAll()
.antMatchers("/oauth/my_approval_page").permitAll()
.antMatchers("/oauth/my_error_page").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/oauth/index")
.loginProcessingUrl("/oauth/login");
}
@Autowired
private CustomAuthenticationProvider authenticationProvider;
}
@Configuration
@MapperScan("com.rensanning")
@EnableTransactionManagement(proxyTargetClass = true)
static class RepositoryConfig {
}
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
@Autowired
private AccountService accountService;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String name = authentication.getName();
String password = authentication.getCredentials().toString();
Account account = accountService.authUser(name, password);
if (account == null) {
throw new AuthenticationCredentialsNotFoundException("Account is not found.");
}
List grantedAuths = AuthorityUtils.createAuthorityList(account.getRoleString());
return new UsernamePasswordAuthenticationToken(name, password, grantedAuths);
}
@Override
public boolean supports(Class> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}
@Service
public class AccountService {
@Autowired
private AccountRepository accountRepository;
public Account authUser(String userName, String password) {
Account u = accountRepository.findByUserName(userName);
if (u == null) {
return null;
}
if (!u.getPassword().equals(password)) {
return null;
}
return u;
}
}
public interface AccountRepository {
@Select("select id, user_name as userName, email, password, role_string as roleString from account where user_name=#{user_name}")
Account findByUserName(String userName);
}
@SuppressWarnings("serial")
public class Account implements Serializable {
private Integer id;
private String userName;
private String email;
private String password;
private String roleString;
// ...setter/getter
}