5/11/2018 - 5:43 PM

Level of Security with Spring and Angular, using JHipster

Defining authorization to certain methods and APIs with Spring as a server and using Angular as client. This snippet doesn't show how to configure the security, only how to set the level of security.

Spring On Spring, the level of security may be set at a lower or higher level.

  • for a lower level perspective, configure the WebSecurityConnfigurerAdapter, setting the access to each endpoint.
  • for a higher level perspective, use the @PreAuthorize anotation on the method signature that you want to secure. The security will be checked before the method is accessed, throwing an unauthorized exception in the case of a violation. It is also possible to use the @PostAuthorize to assert the security after the method's execution

Angular JHipster has an directive to check the authority set for the user, the jhiHasAnyAuthority="'{ROLE}". It conditionally includes an HTML element if current user has any * of the authorities passed as the expression.

Conditionally includes an HTML element if current user has any
of the authorities passed as the `expression`.

<some-element *jhiHasAnyAuthority="'ROLE_ADMIN'">...</some-element>

<some-element *jhiHasAnyAuthority="['ROLE_ADMIN', 'ROLE_USER']">...</some-element>
public class RestController {
  // set the autorization level before the access of the method
  public ResponseEntity<Resposta> createResposta(@Valid @RequestBody Resposta resposta) throws URISyntaxException {
    // ....
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
  // ....
  // static resources are ignored by security
    public void configure(WebSecurity web) throws Exception {
            .antMatchers(HttpMethod.OPTIONS, "/**")
    protected void configure(HttpSecurity http) throws Exception {
            .addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class)
            // set access privileges at a lower level here
            // define the api's address and the level of security