我是一種新的Apache shiro,並嘗試使用authcBasic來保護web服務。apache Shiro登錄
我需要創建一個web服務,我可以通過提供用戶名和密碼來登錄,這可以利用Apache shiro的功能。
任何指導意見將非常理解
我是一種新的Apache shiro,並嘗試使用authcBasic來保護web服務。apache Shiro登錄
我需要創建一個web服務,我可以通過提供用戶名和密碼來登錄,這可以利用Apache shiro的功能。
任何指導意見將非常理解
我已創建了彈簧引導一個最小的示例應用程序(因爲「春天」的標籤)和四郎給你,你可以找到here on GitHub。示例應用程序基於Spring文檔中的"hello world" RESTful web service with Spring application。我已經通過these changes (GitHub commit)添加四郎它:從Shiro docs
</dependencies>
[...]
<!-- Apache Shiro -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.3.2</version>
</dependency>
</dependencies>
複製shiro.ini資源:
添加shiro-spring
依賴關係的pom.xml
# =============================================================================
# Tutorial INI configuration
#
# Usernames/passwords are based on the classic Mel Brooks' film "Spaceballs" :)
# =============================================================================
# -----------------------------------------------------------------------------
# Users and their (optional) assigned roles
# username = password, role1, role2, ..., roleN
# -----------------------------------------------------------------------------
[users]
root = secret, admin
guest = guest, guest
presidentskroob = 12345, president
darkhelmet = ludicrousspeed, darklord, schwartz
lonestarr = vespa, goodguy, schwartz
# -----------------------------------------------------------------------------
# Roles with assigned permissions
# roleName = perm1, perm2, ..., permN
# -----------------------------------------------------------------------------
[roles]
admin = *
schwartz = lightsaber:*
goodguy = winnebago:drive:eagle5
配置ShiroFilter,SecurityManager與IniRealm和Shiro annotations在Application.java(改編自here):
@SpringBootApplication
public class Application {
[...]
@Bean(name = "shiroFilter")
public FilterRegistrationBean shiroFilter() throws Exception {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter((AbstractShiroFilter) getShiroFilterFactoryBean().getObject());
registration.setDispatcherTypes(EnumSet.allOf(DispatcherType.class));
return registration;
}
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean() {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager());
Map<String, String> filterChainDefinitionMap = shiroFilterFactoryBean.getFilterChainDefinitionMap();
filterChainDefinitionMap.put("/**", "authcBasic");
return shiroFilterFactoryBean;
}
@Bean(name = "securityManager")
public DefaultWebSecurityManager securityManager() {
DefaultWebSecurityManager dwsm = new DefaultWebSecurityManager();
dwsm.setRealm(getShiroIniRealm());
final DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
// disable session cookie
sessionManager.setSessionIdCookieEnabled(false);
dwsm.setSessionManager(sessionManager);
return dwsm;
}
@Bean(name = "shiroIniRealm")
@DependsOn("lifecycleBeanPostProcessor")
public IniRealm getShiroIniRealm() {
return new IniRealm("classpath:shiro.ini");
}
@Bean(name = "lifecycleBeanPostProcessor")
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor();
}
@Bean
public DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator daap = new DefaultAdvisorAutoProxyCreator();
daap.setProxyTargetClass(true);
return daap;
}
@Bean
public AuthorizationAttributeSourceAdvisor getAuthorizationAttributeSourceAdvisor() {
AuthorizationAttributeSourceAdvisor aasa = new AuthorizationAttributeSourceAdvisor();
aasa.setSecurityManager(securityManager());
return new AuthorizationAttributeSourceAdvisor();
}
}
與參數「管理員」添加@RequiresRoles
註釋GreetingController
用於測試目的:
@RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
@RequestMapping("/greeting")
@RequiresRoles(value = {"admin"})
public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
}
}
使用下面的命令來檢查和運行應用程序:
git clone https://github.com/opncow/gs-rest-service.git
cd gs-rest-service/complete/
./mvnw spring-boot:run
驗證四郎是工作(使用HttpRequester或類似的插件來創建以下請求):
用戶「根」(具有「管理員」角色)與密碼「祕密」(Base64編碼的用戶名:作爲授權報頭的值的密碼)
GET http://localhost:8080/greeting
Authorization: Basic cm9vdDpzZWNyZXQ=
-- response --
200
Set-Cookie: rememberMe=deleteMe; Path=/; Max-Age=0; Expires=Thu, 11-May-2017 00:29:44 GMT
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Fri, 12 May 2017 00:29:44 GMT
{"id":1,"content":"Hello, World!"}
用戶「客人」與口令「客人」(沒有「管理員「角色):
GET http://localhost:8080/greeting
Authorization: Basic Z3Vlc3Q6Z3Vlc3Q=
-- response --
500
Set-Cookie: rememberMe=deleteMe; Path=/; Max-Age=0; Expires=Thu, 11-May-2017 00:44:18 GMT rememberMe=deleteMe; Path=/; Max-Age=0; Expires=Thu, 11-May-2017 00:44:18 GMT
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Fri, 12 May 2017 00:44:18 GMT
Connection: close
{"timestamp":1494549858572,"status":500,"error":"Internal Server Error","exception":"org.apache.shiro.authz.UnauthorizedException","message":"Subject does not have role [admin]","path":"/greeting"}
可以看出,在第二個請求,用戶來賓進行身份驗證,但無權使用,因爲缺乏的問候資源‘管理員’的角色(這意味着註釋加工)。
這是我能想象的最簡單的例子。它使用Shiro的.ini配置/領域用戶,密碼和角色。對於真實世界的項目,您可能必須使用更復雜的領域實施,例如Shiro的JdbcRealm