0

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?

1
  • 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? Commented Jan 29, 2014 at 12:18

3 Answers 3

1

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')" />
Sign up to request clarification or add additional context in comments.

1 Comment

But I'm using @PreAuthorize in my controller. So I thought that I don't need it. I don't use in the other http section.. Anyway, problem is, that authentication via browser works fine, but not with my REST client.
0

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

1 Comment

I don't use JavaConfig and additionally I have two security contexts (webapp and rest api).
0

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")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.