In this short post I'd like to present a simple configuration of Spring Boot application serving stateless service using basic authentication.
Below a web security configurer implementation including all possible ways to define annotation rule matchers (pre, post processing and jsr250 specification)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | @EnableGlobalMethodSecurity( prePostEnabled = true, securedEnabled = true, jsr250Enabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(final HttpSecurity http) { sessionSettings() .andThen(this::headersSecurity) .andThen(this::accessRules) .unchecked() .accept(http); } private void headersSecurity(final HttpSecurity http) throws Exception { http.sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .csrf() .disable() .httpBasic() .realmName("App"); } private CheckedConsumer<HttpSecurity> sessionSettings() { return http -> http .sessionManagement() .sessionCreationPolicy(STATELESS); } @Override protected void configure(final AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("client") .password(passwordEncoder().encode("admin")) .roles("CLIENT"); } ... } |
What is important in code is to define session creation policy.
Then it is possible to implement standard resource.
1 2 3 4 5 6 7 8 9 10 | @RestController @RequestMapping("/service") public class Endpoint { @PostMapping("/endpoint") @Secured("ROLE_CLIENT") public String endpoint(@RequestBody final String req) { return "test"; } } |
Resources:
[1] - Spring Security
No comments:
Post a Comment