Giriş
OAuth ve JWT'nin birlikte kullanımı dışında sadece JWT kullanarak authentication da yapılabilir.
Angular İle Kullanmak
Kullandığımız front end kütüphanesinde (örneğin Angular) bir HttpInterceptor kullanarak tüm dışarı giden (outgoing) Http istekleri için Json Web Token bilgisini eklemek
gerekir.
Adımlar
Adım sırası kabaca
şöyle.
Hemen hemen aynı adımları izleyen bir başka uygulama
burada.
Her iki örnek te token üretmek için
io.jsonwebtoken.Jwts kütüphanesini kullanıyor.
Maven
Şu satırı dahil ederiz
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
JwtAuthenticationRestController Sınıfı
- Uygulama
JwtAuthenticationRestController vasıtasıyla iki tane Rest noktası sunar. Bunlar şöyledir
1. http://localhost:8080/authenticate
Açıklaması
şöyle.
JwtTokenRequest okur ve
JwtTokenResponse döner.
Expose a POST API with mapping /authenticate. On passing the correct username and password, it will generate a JSON Web Token (JWT).
2. http://localhost:8080/refresh
JwtTokenRequest okur ve
JwtTokenResponse döner.
JwtTokenResponse yerine direkt
Response nenesi de dönüleblir.
JwtTokenRequest Sınıfı
Sadece username ve password alanlarından oluşur.
JwtTokenResponse Sınıfı
Sadece token isimli String tipinden bir alandan oluşur.
Jwt Authentication İçin Rest EndpointÖrnek ver
JwtUserDetails Sınıfı
UserDetails arayüzünden kalıtan bir JwtUserDetails sınıfı kodlanır. Bu sınıf kullanıcı hakkında bilgileri içerir.
JwUserDetailsService Sınıfı
UserDetailsService arayüzünden kalıtan bir JwUserDetailsService sınıfı kodlanır. Bu sınıf belirtilen isme ve şifreye sahip JwtUserDetails nesnesini döner veya exception fırlatır.
JwtTokenUtil Sınfı
Token içindeki çeşitli alanları erişimi kolaylaştırır.
WebSecurityConfigurerAdapter Sınıfı
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
@Autowired
private JwtRequestFilter jwtRequestFilter;
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
// dont authenticate this particular request
httpSecurity.authorizeRequests()
.antMatchers("/authenticate").permitAll()
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll().
// all other requests need to be authenticated
anyRequest().authenticated()
.and()
// make sure we use stateless session; session won't be used to
// store user's state.
.exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint)
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
// Add a filter to validate the tokens with every request
httpSecurity.addFilterBefore(jwtRequestFilter,
UsernamePasswordAuthenticationFilter.class);
}
}
JwtAuthenticationEntryPoint Sınıfı
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}
}