JWT Example
1. /authenticate --> Auth Service - Creates JWT.
2. /public/profile --> can be accessed without JWT Token
3. /public/resource --> can be accessed without JWT Token
4. /private/users --> can be accessed with JWT Token
Consider the above endPoints of your application. Here,
/**/public/**
will be accessible to everyone doesn't matter JWT Token
is present or not
/**/private/**
will be accessible to the clients which have JWT
Token. if a token is not present it will response with 401/403
(Unauthorized/Forbidden)
Now coming to the coding part. You have to create one WebSecurityConfig
class which extends WebSecurityConfigurerAdapter
which override the configure(HttpSecurity http)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
{
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.cors().disable()
.authorizeRequests()
.antMatchers("/authenticate").permitAll()
.antMatchers("/**/private/**").authenticated()
.anyRequest().permitAll()
.and()
.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class)
.exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint);
}
}
Change .anyRequest().permitAll() to .anyRequest().authenticated() if you want authenticated all the request.
You can also add endPoints to configure(WebSecurity web) for which you don't want to apply Spring Security Filter Chain.
@Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("**/public/**")
}