SlideShare a Scribd company logo
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
final class FilterComparator implements Comparator<Filter>,
Serializable {
private static final int INITIAL_ORDER = 100;
private static final int ORDER_STEP = 100;
private final Map<String, Integer> filterToOrder =
new HashMap<>();
FilterComparator() {
Step order =
new FilterComparator.Step(INITIAL_ORDER, ORDER_STEP);
put(ChannelProcessingFilter.class, order.next());
put(ConcurrentSessionFilter.class, order.next());
put(WebAsyncManagerIntegrationFilter.class, order.next());
put(SecurityContextPersistenceFilter.class, order.next());
put(HeaderWriterFilter.class, order.next());
put(CorsFilter.class, order.next());
put(CsrfFilter.class, order.next());
put(LogoutFilter.class, order.next());
// ……
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
public interface AccessDecisionVoter<S> {
int ACCESS_GRANTED = 1;
int ACCESS_ABSTAIN = 0;
int ACCESS_DENIED = -1;
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private final UserDetailsServiceImpl userDetailsService;
// ……
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/js/**", "/css/**", "/webjars/**").permitAll()
.antMatchers("/users/**").hasRole(Role.STAFF.name())
.antMatchers("/**").authenticated()
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/login")
.defaultSuccessUrl("/success", true)
.failureUrl("/login?error=true").permitAll();
}
}
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private final UserDetailsServiceImpl userDetailsService;
// ……
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/js/**", "/css/**", "/webjars/**").permitAll()
.antMatchers("/users/**").hasRole(Role.STAFF.name())
.antMatchers("/**").authenticated()
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/login")
.defaultSuccessUrl("/success", true)
.failureUrl("/login?error=true").permitAll();
}
}
public FormLoginConfigurer() {
super(new UsernamePasswordAuthenticationFilter(),null);
usernameParameter("username");
passwordParameter("password");
}
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
public Authentication attemptAuthentication(
HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
// ……
String username = obtainUsername(request);
String password = obtainPassword(request);
if (username == null) {
username = "";
}
if (password == null) {
password = "";
}
username = username.trim();
UsernamePasswordAuthenticationToken authRequest =
new UsernamePasswordAuthenticationToken(username, password);
setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authRequest);
}
public Authentication attemptAuthentication(
HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
// ……
String username = obtainUsername(request);
String password = obtainPassword(request);
if (username == null) {
username = "";
}
if (password == null) {
password = "";
}
username = username.trim();
UsernamePasswordAuthenticationToken authRequest =
new UsernamePasswordAuthenticationToken(username, password);
setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authRequest);
}
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
// ……
for (AuthenticationProvider provider : getProviders()) {
if (!provider.supports(toTest)) {
continue;
}
// ……
try {
result = provider.authenticate(authentication);
if (result != null) {
copyDetails(authentication, result);
break;
}
}
// ……
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
protected final UserDetails retrieveUser(
String username, UsernamePasswordAuthenticationToken authentication)
throws AuthenticationException {
// ……
try {
UserDetails loadedUser =
this.getUserDetailsService().loadUserByUsername(username);
if (loadedUser == null) {
// ……
}
return loadedUser;
}
// ……
}
@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {
private final UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
User user = userRepository.findByUsername(username)
.orElseThrow(
() -> new UsernameNotFoundException("username not found"));
return new org.springframework.security.core.userdetails.User(
user.getUsername(),
user.getPassword(),
createAuthorityList("ROLE_" + user.getRole().name()));
}
}
protected void additionalAuthenticationChecks(
UserDetails userDetails,
UsernamePasswordAuthenticationToken authentication)
throws AuthenticationException {
// ……
String presentedPassword =
authentication.getCredentials().toString();
if (!passwordEncoder.matches(
presentedPassword, userDetails.getPassword())) {
// ……
throw new BadCredentialsException(messages.getMessage(
"AbstractUserDetailsAuthenticationProvider.badCredentials",
"Bad credentials"));
}
}
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
public class CustomPreAuthenticatedProcessingFilter extends
AbstractPreAuthenticatedProcessingFilter {
@Override
protected Object getPreAuthenticatedPrincipal(
HttpServletRequest request) {
return "";
}
@Override
protected Object getPreAuthenticatedCredentials(
HttpServletRequest request) {
String accessToken =
request.getHeader(HttpHeaders.AUTHORIZATION);
if (StringUtils.isEmpty(accessToken)
|| !accessToken.startsWith("Bearer ")) {
return "";
}
return accessToken.split(" ")[1];
}
}
public class CustomPreAuthenticatedProcessingFilter extends
AbstractPreAuthenticatedProcessingFilter {
@Override
protected Object getPreAuthenticatedPrincipal(
HttpServletRequest request) {
return "";
}
@Override
protected Object getPreAuthenticatedCredentials(
HttpServletRequest request) {
String accessToken =
request.getHeader(HttpHeaders.AUTHORIZATION);
if (StringUtils.isEmpty(accessToken)
|| !accessToken.startsWith("Bearer ")) {
return "";
}
return accessToken.split(" ")[1];
}
}
private void doAuthenticate(
HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
Authentication authResult;
Object principal = getPreAuthenticatedPrincipal(request);
Object credentials = getPreAuthenticatedCredentials(request);
// ……
try {
PreAuthenticatedAuthenticationToken authRequest =
new PreAuthenticatedAuthenticationToken(
principal, credentials);
authRequest.setDetails(
authenticationDetailsSource.buildDetails(request));
authResult = authenticationManager.authenticate(authRequest);
successfulAuthentication(request, response, authResult);
}
catch (AuthenticationException failed) {
// ……
}
}
private void doAuthenticate(
HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
Authentication authResult;
Object principal = getPreAuthenticatedPrincipal(request);
Object credentials = getPreAuthenticatedCredentials(request);
// ……
try {
PreAuthenticatedAuthenticationToken authRequest =
new PreAuthenticatedAuthenticationToken(
principal, credentials);
// ……
authResult = authenticationManager.authenticate(authRequest);
successfulAuthentication(request, response, authResult);
}
catch (AuthenticationException failed) {
// ……
}
}
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
public Authentication authenticate(Authentication auth)
throws AuthenticationException {
String accessToken = Optional.ofNullable(auth.getCredentials())
.map(Object::toString)
.orElse(null);
if (accessToken == null) {
throw new BadCredentialsException("access token not found.");
}
DecodedJWT decodedAccessToken = JWTUtils.decode(accessToken);
// ……
String username = decodedAccessToken.getClaim("username").asString();
UserDetails ud = userDetailsService.loadUserDetails(
new PreAuthenticatedAuthenticationToken(
username, auth.getCredentials());
return new PreAuthenticatedAuthenticationToken(
ud, authentication.getCredentials(), ud.getAuthorities());
}
public Authentication authenticate(Authentication auth)
throws AuthenticationException {
String accessToken = Optional.ofNullable(auth.getCredentials())
.map(Object::toString)
.orElse(null);
if (accessToken == null) {
throw new BadCredentialsException("access token not found.");
}
DecodedJWT decodedAccessToken = JWTUtils.decode(accessToken);
// ……
String username = decodedAccessToken.getClaim("username").asString();
UserDetails ud = userDetailsService.loadUserDetails(
new PreAuthenticatedAuthenticationToken(
username, auth.getCredentials());
return new PreAuthenticatedAuthenticationToken(
ud, authentication.getCredentials(), ud.getAuthorities());
}
public Authentication authenticate(Authentication auth)
throws AuthenticationException {
String accessToken = Optional.ofNullable(auth.getCredentials())
.map(Object::toString)
.orElse(null);
if (accessToken == null) {
throw new BadCredentialsException("access token not found.");
}
DecodedJWT decodedAccessToken = JWTUtils.decode(accessToken);
// …… JWT
String username = decodedAccessToken.getClaim("username").asString();
UserDetails ud = userDetailsService.loadUserDetails(
new PreAuthenticatedAuthenticationToken(
username, auth.getCredentials());
return new PreAuthenticatedAuthenticationToken(
ud, authentication.getCredentials(), ud.getAuthorities());
}
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
@Service
public class CustomAuthenticationUserDetailsService
implements AuthenticationUserDetailsService {
private final CustomUserDetailsService userDetailsService;
// ……
@Override
public UserDetails loadUserDetails(Authentication token)
throws UsernameNotFoundException {
String username = token.getPrincipal().toString();
String accessToken = token.getCredentials().toString();
return
Optional.ofNullable(
userDetailsService.loadUserByUsername(username))
.map(u ->
new CustomUserDetails(
((CustomUserDetails) u).getUser(), accessToken))
.orElseThrow(() ->
new UsernameNotFoundException("user not found"));
}
}
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
<dependencies>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
testCompile “org.springframework.security:spring-
security-test:5.1.1.RELEASE”
@BeforeEach
void beforeEach() {
mockMvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.build();
}
@Test
void loginSuccess() throws Exception {
MvcResult result =
mockMvc
.perform(formLogin()
.user("ruchitate").password("password"))
.andReturn();
Assertions.assertThat(result.getResponse())
.extracting(
MockHttpServletResponse::getStatus,
MockHttpServletResponse::getRedirectedUrl)
.containsExactly(302, "/success");
}
@Test
void useWith200() throws Exception {
MvcResult result = mockMvc.perform(get("/users/{id}", 1)
.with(user("ruchitate").roles("STAFF")))
.andExpect(status().isOk())
.andReturn();
assertEquals(
"{"name":" ","username":"ruchitate",
"createdAt":"2018-10-01T00:00:00","lastSignInAt":null}",
result.getResponse().getContentAsString());
}
@Test
void useWith403ForAdmin() throws Exception {
mockMvc.perform(get("/users/{id}", 1)
.with(user("ruchitate").roles("ADMIN")))
.andExpect(status().isForbidden())
.andReturn();
}
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
@PreAuthorize("hasRole('ADMIN')")
public List<User> list() {
return userRepository.findAll();
}
@PreAuthorize("#role == 'ADMIN'")
public List<User> list(String role) {
return userRepository.findAll();
}
@PreAuthorize("#r.name == 'ruchitate'")
public List<User> list(@P("r") UserRequest request) {
return userRepository.findAll();
}
@PostAuthorize("returnObject != null &&
returnObject.username == 'ruchitate'")
public User get(Integer id) {
return userRepository.findById(id).orElse(null);
}
@PreFilter("filterObject.name.equals('ruchitate')")
public List<User> list(List<UserRequest> requests) {
List<String> usernameList = requests.stream()
.map(UserRequest::getName)
.collect(Collectors.toList());
return userRepository
.findAllByUsernameIn(usernameList);
}
@PostFilter("filterObject.username == 'ruchitate'")
public List<User> list() {
return userRepository.findAll();
}
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Ad

More Related Content

What's hot (20)

Amazon EKS への道 ~ EKS 再入門 ~
Amazon EKS への道 ~ EKS 再入門 ~Amazon EKS への道 ~ EKS 再入門 ~
Amazon EKS への道 ~ EKS 再入門 ~
Hideaki Aoyagi
 
Where狙いのキー、order by狙いのキー
Where狙いのキー、order by狙いのキーWhere狙いのキー、order by狙いのキー
Where狙いのキー、order by狙いのキー
yoku0825
 
SQLアンチパターン 幻の第26章「とりあえず削除フラグ」
SQLアンチパターン 幻の第26章「とりあえず削除フラグ」SQLアンチパターン 幻の第26章「とりあえず削除フラグ」
SQLアンチパターン 幻の第26章「とりあえず削除フラグ」
Takuto Wada
 
Javaのログ出力: 道具と考え方
Javaのログ出力: 道具と考え方Javaのログ出力: 道具と考え方
Javaのログ出力: 道具と考え方
Taku Miyakawa
 
Form認証で学ぶSpring Security入門
Form認証で学ぶSpring Security入門Form認証で学ぶSpring Security入門
Form認証で学ぶSpring Security入門
Ryosuke Uchitate
 
20190911 AWS Black Belt Online Seminar AWS Batch
20190911 AWS Black Belt Online Seminar AWS Batch20190911 AWS Black Belt Online Seminar AWS Batch
20190911 AWS Black Belt Online Seminar AWS Batch
Amazon Web Services Japan
 
とある診断員とSQLインジェクション
とある診断員とSQLインジェクションとある診断員とSQLインジェクション
とある診断員とSQLインジェクション
zaki4649
 
SPAセキュリティ入門~PHP Conference Japan 2021
SPAセキュリティ入門~PHP Conference Japan 2021SPAセキュリティ入門~PHP Conference Japan 2021
SPAセキュリティ入門~PHP Conference Japan 2021
Hiroshi Tokumaru
 
At least onceってぶっちゃけ問題の先送りだったよね #kafkajp
At least onceってぶっちゃけ問題の先送りだったよね #kafkajpAt least onceってぶっちゃけ問題の先送りだったよね #kafkajp
At least onceってぶっちゃけ問題の先送りだったよね #kafkajp
Yahoo!デベロッパーネットワーク
 
Spring Boot × Vue.jsでSPAを作る
Spring Boot × Vue.jsでSPAを作るSpring Boot × Vue.jsでSPAを作る
Spring Boot × Vue.jsでSPAを作る
Go Miyasaka
 
KeycloakでAPI認可に入門する
KeycloakでAPI認可に入門するKeycloakでAPI認可に入門する
KeycloakでAPI認可に入門する
Hitachi, Ltd. OSS Solution Center.
 
Keycloak拡張入門
Keycloak拡張入門Keycloak拡張入門
Keycloak拡張入門
Hiroyuki Wada
 
インフラCICDの勘所
インフラCICDの勘所インフラCICDの勘所
インフラCICDの勘所
Toru Makabe
 
AWSのログ管理ベストプラクティス
AWSのログ管理ベストプラクティスAWSのログ管理ベストプラクティス
AWSのログ管理ベストプラクティス
Akihiro Kuwano
 
20210127 今日から始めるイベントドリブンアーキテクチャ AWS Expert Online #13
20210127 今日から始めるイベントドリブンアーキテクチャ AWS Expert Online #1320210127 今日から始めるイベントドリブンアーキテクチャ AWS Expert Online #13
20210127 今日から始めるイベントドリブンアーキテクチャ AWS Expert Online #13
Amazon Web Services Japan
 
え、まって。その並列分散処理、Kafkaのしくみでもできるの? Apache Kafkaの機能を利用した大規模ストリームデータの並列分散処理
え、まって。その並列分散処理、Kafkaのしくみでもできるの? Apache Kafkaの機能を利用した大規模ストリームデータの並列分散処理え、まって。その並列分散処理、Kafkaのしくみでもできるの? Apache Kafkaの機能を利用した大規模ストリームデータの並列分散処理
え、まって。その並列分散処理、Kafkaのしくみでもできるの? Apache Kafkaの機能を利用した大規模ストリームデータの並列分散処理
NTT DATA Technology & Innovation
 
Amazon Athena 初心者向けハンズオン
Amazon Athena 初心者向けハンズオンAmazon Athena 初心者向けハンズオン
Amazon Athena 初心者向けハンズオン
Amazon Web Services Japan
 
GKE に飛んでくるトラフィックを 自由自在に操る力 | 第 10 回 Google Cloud INSIDE Games & Apps Online
GKE に飛んでくるトラフィックを 自由自在に操る力 | 第 10 回 Google Cloud INSIDE Games & Apps OnlineGKE に飛んでくるトラフィックを 自由自在に操る力 | 第 10 回 Google Cloud INSIDE Games & Apps Online
GKE に飛んでくるトラフィックを 自由自在に操る力 | 第 10 回 Google Cloud INSIDE Games & Apps Online
Google Cloud Platform - Japan
 
外部キー制約に伴うロックの小話
外部キー制約に伴うロックの小話外部キー制約に伴うロックの小話
外部キー制約に伴うロックの小話
ichirin2501
 
マイクロにしすぎた結果がこれだよ!
マイクロにしすぎた結果がこれだよ!マイクロにしすぎた結果がこれだよ!
マイクロにしすぎた結果がこれだよ!
mosa siru
 
Amazon EKS への道 ~ EKS 再入門 ~
Amazon EKS への道 ~ EKS 再入門 ~Amazon EKS への道 ~ EKS 再入門 ~
Amazon EKS への道 ~ EKS 再入門 ~
Hideaki Aoyagi
 
Where狙いのキー、order by狙いのキー
Where狙いのキー、order by狙いのキーWhere狙いのキー、order by狙いのキー
Where狙いのキー、order by狙いのキー
yoku0825
 
SQLアンチパターン 幻の第26章「とりあえず削除フラグ」
SQLアンチパターン 幻の第26章「とりあえず削除フラグ」SQLアンチパターン 幻の第26章「とりあえず削除フラグ」
SQLアンチパターン 幻の第26章「とりあえず削除フラグ」
Takuto Wada
 
Javaのログ出力: 道具と考え方
Javaのログ出力: 道具と考え方Javaのログ出力: 道具と考え方
Javaのログ出力: 道具と考え方
Taku Miyakawa
 
Form認証で学ぶSpring Security入門
Form認証で学ぶSpring Security入門Form認証で学ぶSpring Security入門
Form認証で学ぶSpring Security入門
Ryosuke Uchitate
 
20190911 AWS Black Belt Online Seminar AWS Batch
20190911 AWS Black Belt Online Seminar AWS Batch20190911 AWS Black Belt Online Seminar AWS Batch
20190911 AWS Black Belt Online Seminar AWS Batch
Amazon Web Services Japan
 
とある診断員とSQLインジェクション
とある診断員とSQLインジェクションとある診断員とSQLインジェクション
とある診断員とSQLインジェクション
zaki4649
 
SPAセキュリティ入門~PHP Conference Japan 2021
SPAセキュリティ入門~PHP Conference Japan 2021SPAセキュリティ入門~PHP Conference Japan 2021
SPAセキュリティ入門~PHP Conference Japan 2021
Hiroshi Tokumaru
 
Spring Boot × Vue.jsでSPAを作る
Spring Boot × Vue.jsでSPAを作るSpring Boot × Vue.jsでSPAを作る
Spring Boot × Vue.jsでSPAを作る
Go Miyasaka
 
Keycloak拡張入門
Keycloak拡張入門Keycloak拡張入門
Keycloak拡張入門
Hiroyuki Wada
 
インフラCICDの勘所
インフラCICDの勘所インフラCICDの勘所
インフラCICDの勘所
Toru Makabe
 
AWSのログ管理ベストプラクティス
AWSのログ管理ベストプラクティスAWSのログ管理ベストプラクティス
AWSのログ管理ベストプラクティス
Akihiro Kuwano
 
20210127 今日から始めるイベントドリブンアーキテクチャ AWS Expert Online #13
20210127 今日から始めるイベントドリブンアーキテクチャ AWS Expert Online #1320210127 今日から始めるイベントドリブンアーキテクチャ AWS Expert Online #13
20210127 今日から始めるイベントドリブンアーキテクチャ AWS Expert Online #13
Amazon Web Services Japan
 
え、まって。その並列分散処理、Kafkaのしくみでもできるの? Apache Kafkaの機能を利用した大規模ストリームデータの並列分散処理
え、まって。その並列分散処理、Kafkaのしくみでもできるの? Apache Kafkaの機能を利用した大規模ストリームデータの並列分散処理え、まって。その並列分散処理、Kafkaのしくみでもできるの? Apache Kafkaの機能を利用した大規模ストリームデータの並列分散処理
え、まって。その並列分散処理、Kafkaのしくみでもできるの? Apache Kafkaの機能を利用した大規模ストリームデータの並列分散処理
NTT DATA Technology & Innovation
 
Amazon Athena 初心者向けハンズオン
Amazon Athena 初心者向けハンズオンAmazon Athena 初心者向けハンズオン
Amazon Athena 初心者向けハンズオン
Amazon Web Services Japan
 
GKE に飛んでくるトラフィックを 自由自在に操る力 | 第 10 回 Google Cloud INSIDE Games & Apps Online
GKE に飛んでくるトラフィックを 自由自在に操る力 | 第 10 回 Google Cloud INSIDE Games & Apps OnlineGKE に飛んでくるトラフィックを 自由自在に操る力 | 第 10 回 Google Cloud INSIDE Games & Apps Online
GKE に飛んでくるトラフィックを 自由自在に操る力 | 第 10 回 Google Cloud INSIDE Games & Apps Online
Google Cloud Platform - Japan
 
外部キー制約に伴うロックの小話
外部キー制約に伴うロックの小話外部キー制約に伴うロックの小話
外部キー制約に伴うロックの小話
ichirin2501
 
マイクロにしすぎた結果がこれだよ!
マイクロにしすぎた結果がこれだよ!マイクロにしすぎた結果がこれだよ!
マイクロにしすぎた結果がこれだよ!
mosa siru
 

Similar to Amazon Cognito使って認証したい?それならSpring Security使いましょう! (20)

Jersey Guice AOP
Jersey Guice AOPJersey Guice AOP
Jersey Guice AOP
Domenico Briganti
 
Code generation for alternative languages
Code generation for alternative languagesCode generation for alternative languages
Code generation for alternative languages
Rafael Winterhalter
 
ERRest
ERRestERRest
ERRest
WO Community
 
Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)
Paco de la Cruz
 
What's new in jQuery 1.5
What's new in jQuery 1.5What's new in jQuery 1.5
What's new in jQuery 1.5
Martin Kleppe
 
CDI e as ideias pro futuro do VRaptor
CDI e as ideias pro futuro do VRaptorCDI e as ideias pro futuro do VRaptor
CDI e as ideias pro futuro do VRaptor
Caelum
 
Unit testing CourseSites Apache Filter
Unit testing CourseSites Apache FilterUnit testing CourseSites Apache Filter
Unit testing CourseSites Apache Filter
Wayan Wira
 
An intro to cqrs
An intro to cqrsAn intro to cqrs
An intro to cqrs
Neil Robbins
 
Nestjs MasterClass Slides
Nestjs MasterClass SlidesNestjs MasterClass Slides
Nestjs MasterClass Slides
Nir Kaufman
 
Codemotion appengine
Codemotion appengineCodemotion appengine
Codemotion appengine
Ignacio Coloma
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
javatwo2011
 
Unit testing with mock libs
Unit testing with mock libsUnit testing with mock libs
Unit testing with mock libs
Valentin Kolesnikov
 
Easy rest service using PHP reflection api
Easy rest service using PHP reflection apiEasy rest service using PHP reflection api
Easy rest service using PHP reflection api
Matthieu Aubry
 
Тарас Олексин - Sculpt! Your! Tests!
Тарас Олексин  - Sculpt! Your! Tests!Тарас Олексин  - Sculpt! Your! Tests!
Тарас Олексин - Sculpt! Your! Tests!
DataArt
 
Wicket 6
Wicket 6Wicket 6
Wicket 6
codepitbull
 
Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30) Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30)
Paco de la Cruz
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
John Ferguson Smart Limited
 
Next generation message driven systems with Akka
Next generation message driven systems with AkkaNext generation message driven systems with Akka
Next generation message driven systems with Akka
Johan Andrén
 
#5 (Remote Method Invocation)
#5 (Remote Method Invocation)#5 (Remote Method Invocation)
#5 (Remote Method Invocation)
Ghadeer AlHasan
 
Taming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, MacoscopeTaming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, Macoscope
Macoscope
 
Code generation for alternative languages
Code generation for alternative languagesCode generation for alternative languages
Code generation for alternative languages
Rafael Winterhalter
 
Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)
Paco de la Cruz
 
What's new in jQuery 1.5
What's new in jQuery 1.5What's new in jQuery 1.5
What's new in jQuery 1.5
Martin Kleppe
 
CDI e as ideias pro futuro do VRaptor
CDI e as ideias pro futuro do VRaptorCDI e as ideias pro futuro do VRaptor
CDI e as ideias pro futuro do VRaptor
Caelum
 
Unit testing CourseSites Apache Filter
Unit testing CourseSites Apache FilterUnit testing CourseSites Apache Filter
Unit testing CourseSites Apache Filter
Wayan Wira
 
Nestjs MasterClass Slides
Nestjs MasterClass SlidesNestjs MasterClass Slides
Nestjs MasterClass Slides
Nir Kaufman
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
javatwo2011
 
Easy rest service using PHP reflection api
Easy rest service using PHP reflection apiEasy rest service using PHP reflection api
Easy rest service using PHP reflection api
Matthieu Aubry
 
Тарас Олексин - Sculpt! Your! Tests!
Тарас Олексин  - Sculpt! Your! Tests!Тарас Олексин  - Sculpt! Your! Tests!
Тарас Олексин - Sculpt! Your! Tests!
DataArt
 
Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30) Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30)
Paco de la Cruz
 
Next generation message driven systems with Akka
Next generation message driven systems with AkkaNext generation message driven systems with Akka
Next generation message driven systems with Akka
Johan Andrén
 
#5 (Remote Method Invocation)
#5 (Remote Method Invocation)#5 (Remote Method Invocation)
#5 (Remote Method Invocation)
Ghadeer AlHasan
 
Taming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, MacoscopeTaming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, Macoscope
Macoscope
 
Ad

More from Ryosuke Uchitate (8)

決済サービスのSpring Bootのバージョンを2系に上げた話
決済サービスのSpring Bootのバージョンを2系に上げた話決済サービスのSpring Bootのバージョンを2系に上げた話
決済サービスのSpring Bootのバージョンを2系に上げた話
Ryosuke Uchitate
 
パラレルキャリアがもたらす相乗効果
パラレルキャリアがもたらす相乗効果パラレルキャリアがもたらす相乗効果
パラレルキャリアがもたらす相乗効果
Ryosuke Uchitate
 
Micrometerでメトリクスを収集してAmazon CloudWatchで可視化
Micrometerでメトリクスを収集してAmazon CloudWatchで可視化Micrometerでメトリクスを収集してAmazon CloudWatchで可視化
Micrometerでメトリクスを収集してAmazon CloudWatchで可視化
Ryosuke Uchitate
 
オレはIntelliJ IDEAをこう使っている
 オレはIntelliJ IDEAをこう使っている オレはIntelliJ IDEAをこう使っている
オレはIntelliJ IDEAをこう使っている
Ryosuke Uchitate
 
春だしBannerで遊バナいか?
春だしBannerで遊バナいか?春だしBannerで遊バナいか?
春だしBannerで遊バナいか?
Ryosuke Uchitate
 
ユニットテストのアサーション 流れるようなインターフェースのAssertJを添えて 入門者仕立て
ユニットテストのアサーション 流れるようなインターフェースのAssertJを添えて 入門者仕立てユニットテストのアサーション 流れるようなインターフェースのAssertJを添えて 入門者仕立て
ユニットテストのアサーション 流れるようなインターフェースのAssertJを添えて 入門者仕立て
Ryosuke Uchitate
 
Spring超入門-Springと出会ってから1年半-
Spring超入門-Springと出会ってから1年半-Spring超入門-Springと出会ってから1年半-
Spring超入門-Springと出会ってから1年半-
Ryosuke Uchitate
 
Spring starterによるSpring Boot Starter
Spring starterによるSpring Boot StarterSpring starterによるSpring Boot Starter
Spring starterによるSpring Boot Starter
Ryosuke Uchitate
 
決済サービスのSpring Bootのバージョンを2系に上げた話
決済サービスのSpring Bootのバージョンを2系に上げた話決済サービスのSpring Bootのバージョンを2系に上げた話
決済サービスのSpring Bootのバージョンを2系に上げた話
Ryosuke Uchitate
 
パラレルキャリアがもたらす相乗効果
パラレルキャリアがもたらす相乗効果パラレルキャリアがもたらす相乗効果
パラレルキャリアがもたらす相乗効果
Ryosuke Uchitate
 
Micrometerでメトリクスを収集してAmazon CloudWatchで可視化
Micrometerでメトリクスを収集してAmazon CloudWatchで可視化Micrometerでメトリクスを収集してAmazon CloudWatchで可視化
Micrometerでメトリクスを収集してAmazon CloudWatchで可視化
Ryosuke Uchitate
 
オレはIntelliJ IDEAをこう使っている
 オレはIntelliJ IDEAをこう使っている オレはIntelliJ IDEAをこう使っている
オレはIntelliJ IDEAをこう使っている
Ryosuke Uchitate
 
春だしBannerで遊バナいか?
春だしBannerで遊バナいか?春だしBannerで遊バナいか?
春だしBannerで遊バナいか?
Ryosuke Uchitate
 
ユニットテストのアサーション 流れるようなインターフェースのAssertJを添えて 入門者仕立て
ユニットテストのアサーション 流れるようなインターフェースのAssertJを添えて 入門者仕立てユニットテストのアサーション 流れるようなインターフェースのAssertJを添えて 入門者仕立て
ユニットテストのアサーション 流れるようなインターフェースのAssertJを添えて 入門者仕立て
Ryosuke Uchitate
 
Spring超入門-Springと出会ってから1年半-
Spring超入門-Springと出会ってから1年半-Spring超入門-Springと出会ってから1年半-
Spring超入門-Springと出会ってから1年半-
Ryosuke Uchitate
 
Spring starterによるSpring Boot Starter
Spring starterによるSpring Boot StarterSpring starterによるSpring Boot Starter
Spring starterによるSpring Boot Starter
Ryosuke Uchitate
 
Ad

Recently uploaded (20)

"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G..."Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
Infopitaara
 
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Journal of Soft Computing in Civil Engineering
 
Smart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineeringSmart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineering
rushikeshnavghare94
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ijscai
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Journal of Soft Computing in Civil Engineering
 
QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)
rccbatchplant
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
theory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptxtheory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptx
sanchezvanessa7896
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
Raish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdfRaish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdf
RaishKhanji
 
Metal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistryMetal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistry
mee23nu
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
railway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forgingrailway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forging
Javad Kadkhodapour
 
Oil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdfOil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdf
M7md3li2
 
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G..."Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
Infopitaara
 
Smart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineeringSmart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineering
rushikeshnavghare94
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ijscai
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)
rccbatchplant
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
theory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptxtheory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptx
sanchezvanessa7896
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
Raish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdfRaish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdf
RaishKhanji
 
Metal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistryMetal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistry
mee23nu
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
railway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forgingrailway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forging
Javad Kadkhodapour
 
Oil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdfOil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdf
M7md3li2
 

Amazon Cognito使って認証したい?それならSpring Security使いましょう!

  • 13. final class FilterComparator implements Comparator<Filter>, Serializable { private static final int INITIAL_ORDER = 100; private static final int ORDER_STEP = 100; private final Map<String, Integer> filterToOrder = new HashMap<>(); FilterComparator() { Step order = new FilterComparator.Step(INITIAL_ORDER, ORDER_STEP); put(ChannelProcessingFilter.class, order.next()); put(ConcurrentSessionFilter.class, order.next()); put(WebAsyncManagerIntegrationFilter.class, order.next()); put(SecurityContextPersistenceFilter.class, order.next()); put(HeaderWriterFilter.class, order.next()); put(CorsFilter.class, order.next()); put(CsrfFilter.class, order.next()); put(LogoutFilter.class, order.next()); // ……
  • 26. public interface AccessDecisionVoter<S> { int ACCESS_GRANTED = 1; int ACCESS_ABSTAIN = 0; int ACCESS_DENIED = -1;
  • 40. @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { private final UserDetailsServiceImpl userDetailsService; // …… @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/js/**", "/css/**", "/webjars/**").permitAll() .antMatchers("/users/**").hasRole(Role.STAFF.name()) .antMatchers("/**").authenticated() .and() .formLogin() .loginPage("/login") .loginProcessingUrl("/login") .defaultSuccessUrl("/success", true) .failureUrl("/login?error=true").permitAll(); } }
  • 41. @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { private final UserDetailsServiceImpl userDetailsService; // …… @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/js/**", "/css/**", "/webjars/**").permitAll() .antMatchers("/users/**").hasRole(Role.STAFF.name()) .antMatchers("/**").authenticated() .and() .formLogin() .loginPage("/login") .loginProcessingUrl("/login") .defaultSuccessUrl("/success", true) .failureUrl("/login?error=true").permitAll(); } }
  • 42. public FormLoginConfigurer() { super(new UsernamePasswordAuthenticationFilter(),null); usernameParameter("username"); passwordParameter("password"); }
  • 45. public Authentication attemptAuthentication( HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { // …… String username = obtainUsername(request); String password = obtainPassword(request); if (username == null) { username = ""; } if (password == null) { password = ""; } username = username.trim(); UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password); setDetails(request, authRequest); return this.getAuthenticationManager().authenticate(authRequest); }
  • 46. public Authentication attemptAuthentication( HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { // …… String username = obtainUsername(request); String password = obtainPassword(request); if (username == null) { username = ""; } if (password == null) { password = ""; } username = username.trim(); UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password); setDetails(request, authRequest); return this.getAuthenticationManager().authenticate(authRequest); }
  • 48. public Authentication authenticate(Authentication authentication) throws AuthenticationException { // …… for (AuthenticationProvider provider : getProviders()) { if (!provider.supports(toTest)) { continue; } // …… try { result = provider.authenticate(authentication); if (result != null) { copyDetails(authentication, result); break; } } // ……
  • 50. protected final UserDetails retrieveUser( String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { // …… try { UserDetails loadedUser = this.getUserDetailsService().loadUserByUsername(username); if (loadedUser == null) { // …… } return loadedUser; } // …… }
  • 51. @Service @RequiredArgsConstructor public class UserDetailsServiceImpl implements UserDetailsService { private final UserRepository userRepository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userRepository.findByUsername(username) .orElseThrow( () -> new UsernameNotFoundException("username not found")); return new org.springframework.security.core.userdetails.User( user.getUsername(), user.getPassword(), createAuthorityList("ROLE_" + user.getRole().name())); } }
  • 52. protected void additionalAuthenticationChecks( UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { // …… String presentedPassword = authentication.getCredentials().toString(); if (!passwordEncoder.matches( presentedPassword, userDetails.getPassword())) { // …… throw new BadCredentialsException(messages.getMessage( "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } }
  • 75. public class CustomPreAuthenticatedProcessingFilter extends AbstractPreAuthenticatedProcessingFilter { @Override protected Object getPreAuthenticatedPrincipal( HttpServletRequest request) { return ""; } @Override protected Object getPreAuthenticatedCredentials( HttpServletRequest request) { String accessToken = request.getHeader(HttpHeaders.AUTHORIZATION); if (StringUtils.isEmpty(accessToken) || !accessToken.startsWith("Bearer ")) { return ""; } return accessToken.split(" ")[1]; } }
  • 76. public class CustomPreAuthenticatedProcessingFilter extends AbstractPreAuthenticatedProcessingFilter { @Override protected Object getPreAuthenticatedPrincipal( HttpServletRequest request) { return ""; } @Override protected Object getPreAuthenticatedCredentials( HttpServletRequest request) { String accessToken = request.getHeader(HttpHeaders.AUTHORIZATION); if (StringUtils.isEmpty(accessToken) || !accessToken.startsWith("Bearer ")) { return ""; } return accessToken.split(" ")[1]; } }
  • 77. private void doAuthenticate( HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Authentication authResult; Object principal = getPreAuthenticatedPrincipal(request); Object credentials = getPreAuthenticatedCredentials(request); // …… try { PreAuthenticatedAuthenticationToken authRequest = new PreAuthenticatedAuthenticationToken( principal, credentials); authRequest.setDetails( authenticationDetailsSource.buildDetails(request)); authResult = authenticationManager.authenticate(authRequest); successfulAuthentication(request, response, authResult); } catch (AuthenticationException failed) { // …… } }
  • 78. private void doAuthenticate( HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Authentication authResult; Object principal = getPreAuthenticatedPrincipal(request); Object credentials = getPreAuthenticatedCredentials(request); // …… try { PreAuthenticatedAuthenticationToken authRequest = new PreAuthenticatedAuthenticationToken( principal, credentials); // …… authResult = authenticationManager.authenticate(authRequest); successfulAuthentication(request, response, authResult); } catch (AuthenticationException failed) { // …… } }
  • 81. public Authentication authenticate(Authentication auth) throws AuthenticationException { String accessToken = Optional.ofNullable(auth.getCredentials()) .map(Object::toString) .orElse(null); if (accessToken == null) { throw new BadCredentialsException("access token not found."); } DecodedJWT decodedAccessToken = JWTUtils.decode(accessToken); // …… String username = decodedAccessToken.getClaim("username").asString(); UserDetails ud = userDetailsService.loadUserDetails( new PreAuthenticatedAuthenticationToken( username, auth.getCredentials()); return new PreAuthenticatedAuthenticationToken( ud, authentication.getCredentials(), ud.getAuthorities()); }
  • 82. public Authentication authenticate(Authentication auth) throws AuthenticationException { String accessToken = Optional.ofNullable(auth.getCredentials()) .map(Object::toString) .orElse(null); if (accessToken == null) { throw new BadCredentialsException("access token not found."); } DecodedJWT decodedAccessToken = JWTUtils.decode(accessToken); // …… String username = decodedAccessToken.getClaim("username").asString(); UserDetails ud = userDetailsService.loadUserDetails( new PreAuthenticatedAuthenticationToken( username, auth.getCredentials()); return new PreAuthenticatedAuthenticationToken( ud, authentication.getCredentials(), ud.getAuthorities()); }
  • 83. public Authentication authenticate(Authentication auth) throws AuthenticationException { String accessToken = Optional.ofNullable(auth.getCredentials()) .map(Object::toString) .orElse(null); if (accessToken == null) { throw new BadCredentialsException("access token not found."); } DecodedJWT decodedAccessToken = JWTUtils.decode(accessToken); // …… JWT String username = decodedAccessToken.getClaim("username").asString(); UserDetails ud = userDetailsService.loadUserDetails( new PreAuthenticatedAuthenticationToken( username, auth.getCredentials()); return new PreAuthenticatedAuthenticationToken( ud, authentication.getCredentials(), ud.getAuthorities()); }
  • 85. @Service public class CustomAuthenticationUserDetailsService implements AuthenticationUserDetailsService { private final CustomUserDetailsService userDetailsService; // …… @Override public UserDetails loadUserDetails(Authentication token) throws UsernameNotFoundException { String username = token.getPrincipal().toString(); String accessToken = token.getCredentials().toString(); return Optional.ofNullable( userDetailsService.loadUserByUsername(username)) .map(u -> new CustomUserDetails( ((CustomUserDetails) u).getUser(), accessToken)) .orElseThrow(() -> new UsernameNotFoundException("user not found")); } }
  • 89. @BeforeEach void beforeEach() { mockMvc = MockMvcBuilders .webAppContextSetup(context) .apply(springSecurity()) .build(); }
  • 90. @Test void loginSuccess() throws Exception { MvcResult result = mockMvc .perform(formLogin() .user("ruchitate").password("password")) .andReturn(); Assertions.assertThat(result.getResponse()) .extracting( MockHttpServletResponse::getStatus, MockHttpServletResponse::getRedirectedUrl) .containsExactly(302, "/success"); }
  • 91. @Test void useWith200() throws Exception { MvcResult result = mockMvc.perform(get("/users/{id}", 1) .with(user("ruchitate").roles("STAFF"))) .andExpect(status().isOk()) .andReturn(); assertEquals( "{"name":" ","username":"ruchitate", "createdAt":"2018-10-01T00:00:00","lastSignInAt":null}", result.getResponse().getContentAsString()); }
  • 92. @Test void useWith403ForAdmin() throws Exception { mockMvc.perform(get("/users/{id}", 1) .with(user("ruchitate").roles("ADMIN"))) .andExpect(status().isForbidden()) .andReturn(); }
  • 95. @PreAuthorize("hasRole('ADMIN')") public List<User> list() { return userRepository.findAll(); } @PreAuthorize("#role == 'ADMIN'") public List<User> list(String role) { return userRepository.findAll(); } @PreAuthorize("#r.name == 'ruchitate'") public List<User> list(@P("r") UserRequest request) { return userRepository.findAll(); }
  • 96. @PostAuthorize("returnObject != null && returnObject.username == 'ruchitate'") public User get(Integer id) { return userRepository.findById(id).orElse(null); }
  • 97. @PreFilter("filterObject.name.equals('ruchitate')") public List<User> list(List<UserRequest> requests) { List<String> usernameList = requests.stream() .map(UserRequest::getName) .collect(Collectors.toList()); return userRepository .findAllByUsernameIn(usernameList); }
  • 98. @PostFilter("filterObject.username == 'ruchitate'") public List<User> list() { return userRepository.findAll(); }