0
votes

I'm trying to implement a REST API for my Spring application. As there are resources which might not be accessed by everyone, I need a security layer.

Within this application I'm already using Spring Security (which works perfectly fine) for securing my web application.

I've added the following http configuration to my spring-security.xml:

<http pattern = "/api/**" use-expressions = "true" disable-url-rewriting = "true">
    <http-basic />
</http>

So I would assume that all request that are made to URLs starting with api/ will be secured.

Problem is that I can access my secured methods without any authentications. But if I use a REST client to access it, I receive this error:

message: Full authentication is required to access this resource
description: This request requires HTTP authentication.

I have no idea how to proceed. What is the best way to secure a REST API using Spring Security?

3
How do you access your secured methods that you say you see them without authentication? Through browser? Are you already on a browser with a logged-in user? - nobeh

3 Answers

1
votes

If you use Spring Security in your application, you, probably, already have an <http> section in one of your Spring config files. You can use this section to secure your REST API.

The <http> does not secure anything on its own. You have to add <intercept-url> rules inside it:

<intercept-url pattern="/api/**" access="hasRole('ROLE_USER')" />
0
votes

There is a tuto on the official site of Spring. It is a little more complicated : Official Spring Tuto

0
votes

Just use Spring Security. In <http> tag add: <security:intercept-url pattern="your url" access="hasAnyRole('Your_User_Role1', 'Your_User_Role2')" />.
Or try use annotations. In your spring-config.xml enable security annotations:
<security:global-method-security jsr250-annotations="enabled" pre-post-annotations="enabled" secured-annotations="enabled"/> and in Controller add @PreAuthorize :

@PreAuthorize("hasAnyRole('Your_User_Role1', 'Your_User_Role2')")
@RequestMapping(value = "/address_planing/load_employee_info")