Authentication via HTTP headers (opaque tokens, jws, jwe) for Spring Security.
<dependency>
<groupId>net.optionfactory.spring</groupId>
<artifactId>authentication-tokens</artifactId>
</dependency>
Lines 32 to 121 in 128202c
@RunWith(SpringRunner.class) | |
@ContextConfiguration(classes = { | |
WebConfig.class, | |
SecurityConfig.class | |
}) | |
@WebAppConfiguration | |
public class TokenAuthenticationExampleTest { | |
@Configuration | |
@EnableWebSecurity | |
public static class SecurityConfig { | |
@Bean | |
public SecurityFilterChain security(HttpSecurity http) throws Exception { | |
http.with(HttpHeaderAuthentication.configurer(), c -> { | |
c.jwe(Jwts.SIG.HS256.key().build(), Customizer.withDefaults()); | |
c.token("M2M_SECRET", "principal1", "ROLE_M2M"); | |
c.token("ANOTHER_SECRET", "principal2", "ROLE_ANOTHER"); | |
}); | |
http.authorizeHttpRequests(c -> { | |
c.requestMatchers("/api/m2m").hasRole("M2M"); | |
}); | |
http.exceptionHandling(eh -> { | |
eh.authenticationEntryPoint(UnauthorizedStatusEntryPoint.bearerChallenge()); | |
}); | |
return http.build(); | |
} | |
} | |
@Configuration | |
@EnableWebMvc | |
public static class WebConfig implements WebMvcConfigurer { | |
@Bean | |
public PingController ping() { | |
return new PingController(); | |
} | |
} | |
@Controller | |
public static class PingController { | |
@GetMapping("/api/m2m") | |
public String ping() { | |
return "pong"; | |
} | |
} | |
@Autowired | |
private WebApplicationContext context; | |
private MockMvc mvc; | |
@Before | |
public void setup() { | |
mvc = MockMvcBuilders | |
.webAppContextSetup(context) | |
.apply(SecurityMockMvcConfigurers.springSecurity()) | |
.build(); | |
} | |
@Test | |
public void missingTokenYields401() throws Exception { | |
mvc.perform(get("/api/m2m")) | |
.andExpect(status().isUnauthorized()); | |
} | |
@Test | |
public void invalidTokenYields401() throws Exception { | |
mvc.perform(get("/api/m2m").header("Authorization", "Bearer UNKNOWN")) | |
.andExpect(status().isUnauthorized()); | |
} | |
@Test | |
public void validTokenAndRoleYields200() throws Exception { | |
mvc.perform(get("/api/m2m").header("Authorization", "Bearer M2M_SECRET")) | |
.andExpect(status().isOk()); | |
} | |
@Test | |
public void validTokenWithWrongRoleYields403() throws Exception { | |
mvc.perform(get("/api/m2m").header("Authorization", "Bearer ANOTHER_SECRET")) | |
.andExpect(status().isForbidden()); | |
} | |
} |