Spring Security OAuth 2 Providerのカスタム開発

12246 ワード

Spring OAuth 2デフォルトで提供されている機能は、どうしても需要を満たすことができず、特注が必要です。ここでは一般的ないくつかの特殊開発が必要なところを挙げます。
関連記事:
[url=http://rensanning.iteye.com/blog/2384996」Spring Security OAuth 2 Providerの最小実現[/url]
[url=http://rensanning.iteye.com/blog/2385162」Spring Security OAuth 2 Providerのデータベース記憶[/url]
[url=http://rensanning.iteye.com/blog/2386309」Spring Security OAuth 2 Providerの第三者登録簡単デモンストレーション[/url]
[url=http://rensanning.iteye.com/blog/2386553」Spring Security OAuth 2 Providerのカスタム開発[/url]
[url=http://rensanning.iteye.com/blog/2386766」Spring Security OAuth 2 Providerの統合JWT[/url]
[b](1)カスタム生成授権コード[/b]
デフォルトのルールは6桁のランダム英数です。
既存の生成ルールはAuthortionCodeServicesを拡張することで上書きできます。クリアーAuthortionCodeを上書きすることで任意の生成ルールに設定できます。
例えば、ここで32桁のランダム英数を返すことができます。
@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;
}

}
効果は以下の通りです
[img]http://dl2.iteye.com/upload/attachment/0126/2143/21aa5ff9-b782-386d-8643-dfff179061cd.png[img]
[b](2)トークン[/b]をカスタマイズ生成する。
デフォルトのルールはUUIDです。
Spring OAuth 2はTokenを操作するインターフェースToken Enhancerを提供し、accessTokenとrefshTokenを任意に操作できるようにする。例えば、ここでTokenの中の横線を取り除くことができます。
@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("-", "");
}

}
効果は以下の通りです
[img]http://dl2.iteye.com/upload/attachment/0126/2145/ff21e53b-f0c5-3c2c-ac12-72df7bc9d9f2.png[img]
[b](3)カスタム授権ページ[/b]
デフォルトの定義は以下の通りです。
org.sprigframe ework.security.oauth.2.provider.endpoint.AuthortionEnd point
[quot]prvate String userAprovalPage=「forward:/oauth/confirm_」access";
privte String errorg Page=「forward:/oauth/error」「て」
org.sprigframe ework.security.oauth.2.provider.endpoint.White abell AprovalEndpoint
[quot]@Request Mapping('/oauth/confirm_)access')
public ModelAndView getAccess Confirmation(Map model,HttpServletRequest request)throws Exception{
//…
)[/quot]
org.sprigframe ework.security.oauth.2.provider.endpoint.White abell Errror Endpoint
[quot]@Request Mapping(「//oauth/error」)
public ModelAndView handleError
//…
)[/quot]
新しいURLを設定します
@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";
}
}
//src/main/reources/templates/oauthapproval.

xmlns:th="http://www.thymeleaf.org">

approval







: clientId










//src/main/reources/templates/oautherror.

xmlns:th="http://www.thymeleaf.org">

error







! !


errorSummary





効果は以下の通りです
[img]http://dl2.iteye.com/upload/attachment/0126/2151/a1714717-d5c2-3537-bc6f-8ddb3ee90787.png[img]
[img]http://dl2.iteye.com/upload/attachment/0126/2149/89e4a7f9-7ca9-38cf-adee-5574b27e9c76.png[img]
[b](4)ユーザー登録ページ[/b]
この部分はSpring Securityの範疇に属するべきです。
[b]ユーザーテーブルの作成[/b]
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');
[b]Spring Security[/b]を配置する
@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 {
}
[b]ユーザ登録処理部[/b]
@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
}
[img]http://dl2.iteye.com/upload/attachment/0126/2177/3dd3a570-5a62-37bd-a16e-63c565e936ff.png[img]
完了したClient->ResourreServer->AuthServerの実行過程:
[img]http://dl2.iteye.com/upload/attachment/0126/2179/43f6a1b9-486b-3b4a-acd0-0cba13dd74d1.gif[img]
参考:
https://stackoverflow.com/questions/29618658/spring-how-to-create-a-custom-access-and-refresh-oauth2-token
https://stackoverflow.com/questions/29345508/spring-oauth2-custom-oauth-approval-page-at-oauth-authorize