Spring security without registering a form

I implemented Spring Security Expression in my Spring controller application:

@Controller @RequestMapping("init") public class InitController { @PreAuthorize("hasRole('ROLE_ADMIN')") @RequestMapping(value = "/", method = RequestMethod.GET) public @ResponseBody String home(){ return "This is the init page"; } } 

With this security configuration:

 <http auto-config="true" create-session="stateless" use-expressions="true"> <intercept-url pattern="/_ah*" access="permitAll" /> <intercept-url pattern="/init/*" access="hasRole('ROLE_ADMIN')"/> <intercept-url pattern="/init*" access="hasRole('ROLE_ADMIN')"/> </http> 

When accessing this resource, the Spring default login form is displayed ( http://localhost:8888/spring_security_login ), but I do not want this to happen, and I just want the credentials to be inserted into the request header, for example, x-authorization-key "or whatever matches the script.

What is the possible solution for this?

  • Is it good to have an x-authorization key in the request.
  • If so, how does this relate to Spring’s security mechanism, that is, how does it fit with the expression "hasRole"
  • It is important that my web service is stateless, and each request receives authentication.
  • Finally, how to handle Spring security without having to deal with the Spring login form

heading

+6
source share
1 answer

You should probably read the description that auto-config , then delete it to disable form-login . Your configuration will be clearer if you specifically configure what you want to use.

From your question it is not clear what you want to include x-authorization-key in the header. If you simply authenticate the client ID and shared secret, you can also use basic authentication, as it is already supported out of the box, and you can simply add <http-basic /> to your configuration. If you have something more personal, then you will probably have to implement your own filter and add it to the Spring filter chain to extract the credentials and process them.

How your authentication mechanism fits in is also dependent on what it consists of. Typically, your users will assign roles that load when they authenticate, usually from some database. The hasRole expression simply checks if the current user has the specified role. Often you need to create a UserDetailsService that loads your user information in a standard format that easily connects to the infrastructure. This is described in detail elsewhere. If you really need something more tuned in this GAE integration blog post , you can get detailed information on how you can integrate with a more complex system.

Spring Security will not create or use a session if you use create-session='stateless' .

PS You do not need to include the same security attributes both at the URL level and on your controller that processes the same URL.

+8
source

Source: https://habr.com/ru/post/923026/


All Articles