Securing REST API using custom tokens (stateless, no UI, no cookies, no basic authentication, no OAuth, no login page)

前端 未结 5 1957
轻奢々
轻奢々 2020-12-22 18:05

There are lots of guidelines, sample codes that show how to secure REST API with Spring Security, but most of them assume a web client and talk about login page, redirection

5条回答
  •  萌比男神i
    2020-12-22 18:27

    My sample app does exactly this - securing REST endpoints using Spring Security in a stateless scenario. Individual REST calls are authenticated using an HTTP header. Authentication information is stored on the server side in an in-memory cache and provides the same semantics as those offered by the HTTP session in a typical web application. The app uses the full Spring Security infrastructure with very minimum custom code. No bare filters, no code outside of the Spring Security infrastructure.

    The basic idea is to implement the following four Spring Security components:

    1. org.springframework.security.web.AuthenticationEntryPoint to trap REST calls requiring authentication but missing the required authentication token and thereby deny the requests.
    2. org.springframework.security.core.Authentication to hold the authentication information required for the REST API.
    3. org.springframework.security.authentication.AuthenticationProvider to perform the actual authentication (against a database, an LDAP server, a web service, etc.).
    4. org.springframework.security.web.context.SecurityContextRepository to hold the authentication token in between HTTP requests. In the sample, the implementation saves the token in an EHCACHE instance.

    The sample uses XML configuration but you can easily come up with the equivalent Java config.

提交回复
热议问题