SlideShare a Scribd company logo
1 of 102
Download to read offline
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());
// ……
public interface AccessDecisionVoter<S> {
int ACCESS_GRANTED = 1;
int ACCESS_ABSTAIN = 0;
int ACCESS_DENIED = -1;
@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");
}
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);
}
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;
}
}
// ……
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"));
}
}
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) {
// ……
}
}
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());
}
@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"));
}
}
<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();
}
@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使いましょう!

More Related Content

What's hot

モノリスからマイクロサービスへの移行 ~ストラングラーパターンの検証~(Spring Fest 2020講演資料)
モノリスからマイクロサービスへの移行 ~ストラングラーパターンの検証~(Spring Fest 2020講演資料)モノリスからマイクロサービスへの移行 ~ストラングラーパターンの検証~(Spring Fest 2020講演資料)
モノリスからマイクロサービスへの移行 ~ストラングラーパターンの検証~(Spring Fest 2020講演資料)NTT DATA Technology & Innovation
 
3分でわかるAzureでのService Principal
3分でわかるAzureでのService Principal3分でわかるAzureでのService Principal
3分でわかるAzureでのService PrincipalToru Makabe
 
マルチテナント化で知っておきたいデータベースのこと
マルチテナント化で知っておきたいデータベースのことマルチテナント化で知っておきたいデータベースのこと
マルチテナント化で知っておきたいデータベースのことAmazon Web Services Japan
 
kubernetes初心者がKnative Lambda Runtime触ってみた(Kubernetes Novice Tokyo #13 発表資料)
kubernetes初心者がKnative Lambda Runtime触ってみた(Kubernetes Novice Tokyo #13 発表資料)kubernetes初心者がKnative Lambda Runtime触ってみた(Kubernetes Novice Tokyo #13 発表資料)
kubernetes初心者がKnative Lambda Runtime触ってみた(Kubernetes Novice Tokyo #13 発表資料)NTT DATA Technology & Innovation
 
ホットペッパービューティーにおけるモバイルアプリ向けAPIのBFF/Backend分割
ホットペッパービューティーにおけるモバイルアプリ向けAPIのBFF/Backend分割ホットペッパービューティーにおけるモバイルアプリ向けAPIのBFF/Backend分割
ホットペッパービューティーにおけるモバイルアプリ向けAPIのBFF/Backend分割Recruit Lifestyle Co., Ltd.
 
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 BatchAmazon Web Services Japan
 
20200303 AWS Black Belt Online Seminar AWS Cloud Development Kit (CDK)
20200303 AWS Black Belt Online Seminar AWS Cloud Development Kit (CDK)20200303 AWS Black Belt Online Seminar AWS Cloud Development Kit (CDK)
20200303 AWS Black Belt Online Seminar AWS Cloud Development Kit (CDK)Amazon Web Services Japan
 
AWSとオンプレミスを繋ぐときに知っておきたいルーティングの基礎知識(CCSI監修!)
AWSとオンプレミスを繋ぐときに知っておきたいルーティングの基礎知識(CCSI監修!)AWSとオンプレミスを繋ぐときに知っておきたいルーティングの基礎知識(CCSI監修!)
AWSとオンプレミスを繋ぐときに知っておきたいルーティングの基礎知識(CCSI監修!)Trainocate Japan, Ltd.
 
Grafana LokiではじめるKubernetesロギングハンズオン(NTT Tech Conference #4 ハンズオン資料)
Grafana LokiではじめるKubernetesロギングハンズオン(NTT Tech Conference #4 ハンズオン資料)Grafana LokiではじめるKubernetesロギングハンズオン(NTT Tech Conference #4 ハンズオン資料)
Grafana LokiではじめるKubernetesロギングハンズオン(NTT Tech Conference #4 ハンズオン資料)NTT DATA Technology & Innovation
 
Azure API Management 俺的マニュアル
Azure API Management 俺的マニュアルAzure API Management 俺的マニュアル
Azure API Management 俺的マニュアル貴志 上坂
 
今からでも遅くないDBマイグレーション - Flyway と SchemaSpy の紹介 -
今からでも遅くないDBマイグレーション - Flyway と SchemaSpy の紹介 -今からでも遅くないDBマイグレーション - Flyway と SchemaSpy の紹介 -
今からでも遅くないDBマイグレーション - Flyway と SchemaSpy の紹介 -onozaty
 
分散トレーシングAWS:X-Rayとの上手い付き合い方
分散トレーシングAWS:X-Rayとの上手い付き合い方分散トレーシングAWS:X-Rayとの上手い付き合い方
分散トレーシングAWS:X-Rayとの上手い付き合い方Recruit Lifestyle Co., Ltd.
 
Dockerからcontainerdへの移行
Dockerからcontainerdへの移行Dockerからcontainerdへの移行
Dockerからcontainerdへの移行Akihiro Suda
 
Amazon EKS によるスマホゲームのバックエンド運用事例
Amazon EKS によるスマホゲームのバックエンド運用事例Amazon EKS によるスマホゲームのバックエンド運用事例
Amazon EKS によるスマホゲームのバックエンド運用事例gree_tech
 
Istioサービスメッシュ入門
Istioサービスメッシュ入門Istioサービスメッシュ入門
Istioサービスメッシュ入門Yoichi Kawasaki
 
Awsをオンプレドメコンに連携させる
Awsをオンプレドメコンに連携させるAwsをオンプレドメコンに連携させる
Awsをオンプレドメコンに連携させるSyuichi Murashima
 
マルチテナントのアプリケーション実装〜実践編〜
マルチテナントのアプリケーション実装〜実践編〜マルチテナントのアプリケーション実装〜実践編〜
マルチテナントのアプリケーション実装〜実践編〜Yoshiki Nakagawa
 
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 OnlineGoogle Cloud Platform - Japan
 

What's hot (20)

モノリスからマイクロサービスへの移行 ~ストラングラーパターンの検証~(Spring Fest 2020講演資料)
モノリスからマイクロサービスへの移行 ~ストラングラーパターンの検証~(Spring Fest 2020講演資料)モノリスからマイクロサービスへの移行 ~ストラングラーパターンの検証~(Spring Fest 2020講演資料)
モノリスからマイクロサービスへの移行 ~ストラングラーパターンの検証~(Spring Fest 2020講演資料)
 
3分でわかるAzureでのService Principal
3分でわかるAzureでのService Principal3分でわかるAzureでのService Principal
3分でわかるAzureでのService Principal
 
マルチテナント化で知っておきたいデータベースのこと
マルチテナント化で知っておきたいデータベースのことマルチテナント化で知っておきたいデータベースのこと
マルチテナント化で知っておきたいデータベースのこと
 
kubernetes初心者がKnative Lambda Runtime触ってみた(Kubernetes Novice Tokyo #13 発表資料)
kubernetes初心者がKnative Lambda Runtime触ってみた(Kubernetes Novice Tokyo #13 発表資料)kubernetes初心者がKnative Lambda Runtime触ってみた(Kubernetes Novice Tokyo #13 発表資料)
kubernetes初心者がKnative Lambda Runtime触ってみた(Kubernetes Novice Tokyo #13 発表資料)
 
ホットペッパービューティーにおけるモバイルアプリ向けAPIのBFF/Backend分割
ホットペッパービューティーにおけるモバイルアプリ向けAPIのBFF/Backend分割ホットペッパービューティーにおけるモバイルアプリ向けAPIのBFF/Backend分割
ホットペッパービューティーにおけるモバイルアプリ向けAPIのBFF/Backend分割
 
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
 
20200303 AWS Black Belt Online Seminar AWS Cloud Development Kit (CDK)
20200303 AWS Black Belt Online Seminar AWS Cloud Development Kit (CDK)20200303 AWS Black Belt Online Seminar AWS Cloud Development Kit (CDK)
20200303 AWS Black Belt Online Seminar AWS Cloud Development Kit (CDK)
 
AWSとオンプレミスを繋ぐときに知っておきたいルーティングの基礎知識(CCSI監修!)
AWSとオンプレミスを繋ぐときに知っておきたいルーティングの基礎知識(CCSI監修!)AWSとオンプレミスを繋ぐときに知っておきたいルーティングの基礎知識(CCSI監修!)
AWSとオンプレミスを繋ぐときに知っておきたいルーティングの基礎知識(CCSI監修!)
 
Grafana LokiではじめるKubernetesロギングハンズオン(NTT Tech Conference #4 ハンズオン資料)
Grafana LokiではじめるKubernetesロギングハンズオン(NTT Tech Conference #4 ハンズオン資料)Grafana LokiではじめるKubernetesロギングハンズオン(NTT Tech Conference #4 ハンズオン資料)
Grafana LokiではじめるKubernetesロギングハンズオン(NTT Tech Conference #4 ハンズオン資料)
 
Infrastructure as Code (IaC) 談義 2022
Infrastructure as Code (IaC) 談義 2022Infrastructure as Code (IaC) 談義 2022
Infrastructure as Code (IaC) 談義 2022
 
Azure API Management 俺的マニュアル
Azure API Management 俺的マニュアルAzure API Management 俺的マニュアル
Azure API Management 俺的マニュアル
 
KeycloakでAPI認可に入門する
KeycloakでAPI認可に入門するKeycloakでAPI認可に入門する
KeycloakでAPI認可に入門する
 
今からでも遅くないDBマイグレーション - Flyway と SchemaSpy の紹介 -
今からでも遅くないDBマイグレーション - Flyway と SchemaSpy の紹介 -今からでも遅くないDBマイグレーション - Flyway と SchemaSpy の紹介 -
今からでも遅くないDBマイグレーション - Flyway と SchemaSpy の紹介 -
 
分散トレーシングAWS:X-Rayとの上手い付き合い方
分散トレーシングAWS:X-Rayとの上手い付き合い方分散トレーシングAWS:X-Rayとの上手い付き合い方
分散トレーシングAWS:X-Rayとの上手い付き合い方
 
Dockerからcontainerdへの移行
Dockerからcontainerdへの移行Dockerからcontainerdへの移行
Dockerからcontainerdへの移行
 
Amazon EKS によるスマホゲームのバックエンド運用事例
Amazon EKS によるスマホゲームのバックエンド運用事例Amazon EKS によるスマホゲームのバックエンド運用事例
Amazon EKS によるスマホゲームのバックエンド運用事例
 
Istioサービスメッシュ入門
Istioサービスメッシュ入門Istioサービスメッシュ入門
Istioサービスメッシュ入門
 
Awsをオンプレドメコンに連携させる
Awsをオンプレドメコンに連携させるAwsをオンプレドメコンに連携させる
Awsをオンプレドメコンに連携させる
 
マルチテナントのアプリケーション実装〜実践編〜
マルチテナントのアプリケーション実装〜実践編〜マルチテナントのアプリケーション実装〜実践編〜
マルチテナントのアプリケーション実装〜実践編〜
 
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
 

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

Code generation for alternative languages
Code generation for alternative languagesCode generation for alternative languages
Code generation for alternative languagesRafael Winterhalter
 
Form認証で学ぶSpring Security入門
Form認証で学ぶSpring Security入門Form認証で学ぶSpring Security入門
Form認証で学ぶSpring Security入門Ryosuke Uchitate
 
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.5Martin 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 VRaptorCaelum
 
Unit testing CourseSites Apache Filter
Unit testing CourseSites Apache FilterUnit testing CourseSites Apache Filter
Unit testing CourseSites Apache FilterWayan Wira
 
Nestjs MasterClass Slides
Nestjs MasterClass SlidesNestjs MasterClass Slides
Nestjs MasterClass SlidesNir Kaufman
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotationjavatwo2011
 
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 apiMatthieu 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 AkkaJohan Andrén
 
#5 (Remote Method Invocation)
#5 (Remote Method Invocation)#5 (Remote Method Invocation)
#5 (Remote Method Invocation)Ghadeer AlHasan
 

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

Jersey Guice AOP
Jersey Guice AOPJersey Guice AOP
Jersey Guice AOP
 
Code generation for alternative languages
Code generation for alternative languagesCode generation for alternative languages
Code generation for alternative languages
 
ERRest
ERRestERRest
ERRest
 
Form認証で学ぶSpring Security入門
Form認証で学ぶSpring Security入門Form認証で学ぶSpring Security入門
Form認証で学ぶSpring Security入門
 
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)
 
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
 
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
 
Unit testing CourseSites Apache Filter
Unit testing CourseSites Apache FilterUnit testing CourseSites Apache Filter
Unit testing CourseSites Apache Filter
 
An intro to cqrs
An intro to cqrsAn intro to cqrs
An intro to cqrs
 
Nestjs MasterClass Slides
Nestjs MasterClass SlidesNestjs MasterClass Slides
Nestjs MasterClass Slides
 
Codemotion appengine
Codemotion appengineCodemotion appengine
Codemotion appengine
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
Unit testing with mock libs
Unit testing with mock libsUnit testing with mock libs
Unit testing with mock libs
 
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
 
Тарас Олексин - Sculpt! Your! Tests!
Тарас Олексин  - Sculpt! Your! Tests!Тарас Олексин  - Sculpt! Your! Tests!
Тарас Олексин - Sculpt! Your! Tests!
 
Wicket 6
Wicket 6Wicket 6
Wicket 6
 
Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30) Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30)
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
 
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
 
#5 (Remote Method Invocation)
#5 (Remote Method Invocation)#5 (Remote Method Invocation)
#5 (Remote Method Invocation)
 

More from 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 StarterRyosuke Uchitate
 

More from Ryosuke Uchitate (8)

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

Recently uploaded

What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 

Recently uploaded (20)

What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 

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

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 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()); // ……
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26. public interface AccessDecisionVoter<S> { int ACCESS_GRANTED = 1; int ACCESS_ABSTAIN = 0; int ACCESS_DENIED = -1;
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 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"); }
  • 43.
  • 44.
  • 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); }
  • 47.
  • 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; } } // ……
  • 49.
  • 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")); } }
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 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) { // …… } }
  • 79.
  • 80.
  • 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()); }
  • 84.
  • 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")); } }
  • 86.
  • 87.
  • 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(); }
  • 93.
  • 94.
  • 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(); }