Grails(16)Secure the REST API-Basic Auth

本文介绍如何使用 Spring Security 插件为 Grails 应用中的 REST API 配置基本认证(Basic Auth),包括配置文件的具体设置、排除不需要认证的路径以及通过单元测试验证认证过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Grails(16)Secure the REST API-Basic Auth
Here are my configuration in Config.groovy
// Added by the Spring Security Core plugin:
grails.plugins.springsecurity.userLookup.userDomainClassName = 'com.sillycat.project.security.BrandUser'
grails.plugins.springsecurity.userLookup.authorityJoinClassName = 'com.sillycat.project.security.BrandUserSecurityRole'
grails.plugins.springsecurity.authority.className = 'com.sillycat.project.security.SecurityRole'
grails.plugins.springsecurity.userLookup.usernamePropertyName = 'email'

//Enable Basic Auth Filter
grails.plugins.springsecurity.useBasicAuth = true
grails.plugins.springsecurity.basic.realmName = "sillycat"

//Exclude normal controllers from basic auth filter. Just the JSON API is included
grails.plugins.springsecurity.filterChain.chainMap = [
'/location/**': 'JOINED_FILTERS,-exceptionTranslationFilter',
'/**': 'JOINED_FILTERS,-basicAuthenticationFilter,-basicExceptionTranslationFilter'
]

grails.plugins.springsecurity.securityConfigType = "InterceptUrlMap"
grails.plugins.springsecurity.interceptUrlMap = [
'/css/**': ['IS_AUTHENTICATED_ANONYMOUSLY'],
'/common.css': ['IS_AUTHENTICATED_ANONYMOUSLY'],
'/favicon.ico': ['IS_AUTHENTICATED_ANONYMOUSLY'],
'/images/**': ['IS_AUTHENTICATED_ANONYMOUSLY'],
'/js/**': ['IS_AUTHENTICATED_ANONYMOUSLY'],
'/login/**': ['IS_AUTHENTICATED_ANONYMOUSLY'],
'/logout/**': ['IS_AUTHENTICATED_ANONYMOUSLY'],
'/register/**': ['IS_AUTHENTICATED_ANONYMOUSLY'],
'/error/**': ['IS_AUTHENTICATED_ANONYMOUSLY'],
//'/location/**': ['IS_AUTHENTICATED_ANONYMOUSLY'],
'/**': ['IS_AUTHENTICATED_REMEMBERED']
]

Here I have 2 kind of configurations now, 1 is for page secure, the other is basic auth, it is for the api part.

Beside the Controller REST API action, there is a annotation
@Secured(["ROLE_USER"])

My test case will be like this to send the basic auth from the header
@Test
publicvoid testGetSuccessswithServer(){
def client = new RESTClient("http://localhost:8080")
client.auth.basic 'username', 'password'
defresponse = client.get(path: "location/1")
System.out.println(response.status)
System.out.println(response.data)
}


Or I can use POSTMAN to verify my API. There is a tab menu named Basic Auth, just put the user name and password.

The basic authority can work alone, but they can not work together.

References:
http://grails-plugins.github.com/grails-spring-security-core/docs/manual/

http://dead-knight.iteye.com/blog/1520080
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值