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使いましょう!

More Related Content

What's hot (20)

PPTX
RLSを用いたマルチテナント実装 for Django
Takayuki Shimizukawa
 
PDF
ビッグデータ処理データベースの全体像と使い分け
Recruit Technologies
 
PDF
Spring Security 5.0 解剖速報
Takuya Iwatsuka
 
PDF
今さらだけどMySQLとライセンス
Hidenori Ishii
 
PDF
なかったらINSERTしたいし、あるならロック取りたいやん?
ichirin2501
 
PPTX
テストコードの DRY と DAMP
Yusuke Kagata
 
PPTX
MQ入門
HIRA
 
PDF
マイクロサービス時代の認証と認可 - AWS Dev Day Tokyo 2018 #AWSDevDay
都元ダイスケ Miyamoto
 
PPTX
PostgreSQLクエリ実行の基礎知識 ~Explainを読み解こう~
Miki Shimogai
 
PDF
ドメイン駆動設計 基本を理解する
増田 亨
 
PPTX
MongoDBが遅いときの切り分け方法
Tetsutaro Watanabe
 
PDF
これからSpringを使う開発者が知っておくべきこと
土岐 孝平
 
PPTX
NginxとLuaを用いた動的なリバースプロキシでデプロイを 100 倍速くした
toshi_pp
 
PDF
【Spring fest 2019】徹底解剖Spring MVCアーキテクチャー
ssuser070fa9
 
PDF
怖くないSpring Bootのオートコンフィグレーション
土岐 孝平
 
PDF
導入から 10 年、PHP の trait は滅びるべきなのか その適切な使いどころと弱点、将来について
shinjiigarashi
 
PDF
ゲームアーキテクチャパターン (Aurora Serverless / DynamoDB)
Amazon Web Services Japan
 
PDF
Keycloak拡張入門
Hiroyuki Wada
 
PDF
[AWS EXpert Online for JAWS-UG 18] 見せてやるよ、Step Functions の本気ってやつをな
Amazon Web Services Japan
 
PDF
Java開発の強力な相棒として今すぐ使えるGroovy
Yasuharu Nakano
 
RLSを用いたマルチテナント実装 for Django
Takayuki Shimizukawa
 
ビッグデータ処理データベースの全体像と使い分け
Recruit Technologies
 
Spring Security 5.0 解剖速報
Takuya Iwatsuka
 
今さらだけどMySQLとライセンス
Hidenori Ishii
 
なかったらINSERTしたいし、あるならロック取りたいやん?
ichirin2501
 
テストコードの DRY と DAMP
Yusuke Kagata
 
MQ入門
HIRA
 
マイクロサービス時代の認証と認可 - AWS Dev Day Tokyo 2018 #AWSDevDay
都元ダイスケ Miyamoto
 
PostgreSQLクエリ実行の基礎知識 ~Explainを読み解こう~
Miki Shimogai
 
ドメイン駆動設計 基本を理解する
増田 亨
 
MongoDBが遅いときの切り分け方法
Tetsutaro Watanabe
 
これからSpringを使う開発者が知っておくべきこと
土岐 孝平
 
NginxとLuaを用いた動的なリバースプロキシでデプロイを 100 倍速くした
toshi_pp
 
【Spring fest 2019】徹底解剖Spring MVCアーキテクチャー
ssuser070fa9
 
怖くないSpring Bootのオートコンフィグレーション
土岐 孝平
 
導入から 10 年、PHP の trait は滅びるべきなのか その適切な使いどころと弱点、将来について
shinjiigarashi
 
ゲームアーキテクチャパターン (Aurora Serverless / DynamoDB)
Amazon Web Services Japan
 
Keycloak拡張入門
Hiroyuki Wada
 
[AWS EXpert Online for JAWS-UG 18] 見せてやるよ、Step Functions の本気ってやつをな
Amazon Web Services Japan
 
Java開発の強力な相棒として今すぐ使えるGroovy
Yasuharu Nakano
 

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

PDF
From 0 to Spring Security 4.0
robwinch
 
PDF
Hacking the Grails Spring Security Plugins
GR8Conf
 
PDF
Security enforcement of Java Microservices with Apiman & Keycloak
Charles Moulliard
 
PPTX
Spring Security 3
Jason Ferguson
 
PDF
Building layers of defense for your application
VMware Tanzu
 
PDF
Java Web Application Security with Java EE, Spring Security and Apache Shiro ...
Matt Raible
 
PDF
Java Web Application Security with Java EE, Spring Security and Apache Shiro ...
Matt Raible
 
PDF
Lesson_07_Spring_Security_Register_NEW.pdf
Scott Anderson
 
PDF
Lesson07_Spring_Security_API.pdf
Scott Anderson
 
PDF
Fun With Spring Security
Burt Beckwith
 
From 0 to Spring Security 4.0
robwinch
 
Hacking the Grails Spring Security Plugins
GR8Conf
 
Security enforcement of Java Microservices with Apiman & Keycloak
Charles Moulliard
 
Spring Security 3
Jason Ferguson
 
Building layers of defense for your application
VMware Tanzu
 
Java Web Application Security with Java EE, Spring Security and Apache Shiro ...
Matt Raible
 
Java Web Application Security with Java EE, Spring Security and Apache Shiro ...
Matt Raible
 
Lesson_07_Spring_Security_Register_NEW.pdf
Scott Anderson
 
Lesson07_Spring_Security_API.pdf
Scott Anderson
 
Fun With Spring Security
Burt Beckwith
 
Ad

More from Ryosuke Uchitate (9)

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

Recently uploaded (20)

PPTX
quantum computing transition from classical mechanics.pptx
gvlbcy
 
PPTX
business incubation centre aaaaaaaaaaaaaa
hodeeesite4
 
PDF
Zero Carbon Building Performance standard
BassemOsman1
 
PDF
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
PPTX
22PCOAM21 Session 1 Data Management.pptx
Guru Nanak Technical Institutions
 
PPTX
Online Cab Booking and Management System.pptx
diptipaneri80
 
PDF
settlement FOR FOUNDATION ENGINEERS.pdf
Endalkazene
 
PPTX
Ground improvement techniques-DEWATERING
DivakarSai4
 
PDF
20ME702-Mechatronics-UNIT-1,UNIT-2,UNIT-3,UNIT-4,UNIT-5, 2025-2026
Mohanumar S
 
PPTX
MULTI LEVEL DATA TRACKING USING COOJA.pptx
dollysharma12ab
 
PDF
IEEE EMBC 2025 「Improving electrolaryngeal speech enhancement via a represent...
NU_I_TODALAB
 
PPTX
MSME 4.0 Template idea hackathon pdf to understand
alaudeenaarish
 
PDF
Packaging Tips for Stainless Steel Tubes and Pipes
heavymetalsandtubes
 
PPTX
Precedence and Associativity in C prog. language
Mahendra Dheer
 
PDF
Introduction to Ship Engine Room Systems.pdf
Mahmoud Moghtaderi
 
PDF
Jual GPS Geodetik CHCNAV i93 IMU-RTK Lanjutan dengan Survei Visual
Budi Minds
 
PPTX
Sensor IC System Design Using COMSOL Multiphysics 2025-July.pptx
James D.B. Wang, PhD
 
PDF
CFM 56-7B - Engine General Familiarization. PDF
Gianluca Foro
 
PDF
EVS+PRESENTATIONS EVS+PRESENTATIONS like
saiyedaqib429
 
PDF
Machine Learning All topics Covers In This Single Slides
AmritTiwari19
 
quantum computing transition from classical mechanics.pptx
gvlbcy
 
business incubation centre aaaaaaaaaaaaaa
hodeeesite4
 
Zero Carbon Building Performance standard
BassemOsman1
 
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
22PCOAM21 Session 1 Data Management.pptx
Guru Nanak Technical Institutions
 
Online Cab Booking and Management System.pptx
diptipaneri80
 
settlement FOR FOUNDATION ENGINEERS.pdf
Endalkazene
 
Ground improvement techniques-DEWATERING
DivakarSai4
 
20ME702-Mechatronics-UNIT-1,UNIT-2,UNIT-3,UNIT-4,UNIT-5, 2025-2026
Mohanumar S
 
MULTI LEVEL DATA TRACKING USING COOJA.pptx
dollysharma12ab
 
IEEE EMBC 2025 「Improving electrolaryngeal speech enhancement via a represent...
NU_I_TODALAB
 
MSME 4.0 Template idea hackathon pdf to understand
alaudeenaarish
 
Packaging Tips for Stainless Steel Tubes and Pipes
heavymetalsandtubes
 
Precedence and Associativity in C prog. language
Mahendra Dheer
 
Introduction to Ship Engine Room Systems.pdf
Mahmoud Moghtaderi
 
Jual GPS Geodetik CHCNAV i93 IMU-RTK Lanjutan dengan Survei Visual
Budi Minds
 
Sensor IC System Design Using COMSOL Multiphysics 2025-July.pptx
James D.B. Wang, PhD
 
CFM 56-7B - Engine General Familiarization. PDF
Gianluca Foro
 
EVS+PRESENTATIONS EVS+PRESENTATIONS like
saiyedaqib429
 
Machine Learning All topics Covers In This Single Slides
AmritTiwari19
 

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(); }