@RestController
public class ServiceController {
@RequestMapping("/hello")
public String hello1(String[] param1, String param2) {
return "hello" + param1[0] + param1[1] + param2;
}
}
//使用指定的密码对内容生成消息摘要(散列值) public static String digest(String key, String content); //使用指定的密码对整个Map的内容生成消息摘要(散列值) public static String digest(String key, Map<String, ?> map)
public class StatelessDefaultSubjectFactory extends DefaultWebSubjectFactory {
public Subject createSubject(SubjectContext context) {
//不创建session
context.setSessionCreationEnabled(false);
return super.createSubject(context);
}
}
public class StatelessAuthcFilter extends AccessControlFilter {
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
return false;
}
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
//1、客户端生成的消息摘要
String clientDigest = request.getParameter(Constants.PARAM_DIGEST);
//2、客户端传入的用户身份
String username = request.getParameter(Constants.PARAM_USERNAME);
//3、客户端请求的参数列表
Map<String, String[]> params =
new HashMap<String, String[]>(request.getParameterMap());
params.remove(Constants.PARAM_DIGEST);
//4、生成无状态Token
StatelessToken token = new StatelessToken(username, params, clientDigest);
try {
//5、委托给Realm进行登录
getSubject(request, response).login(token);
} catch (Exception e) {
e.printStackTrace();
onLoginFail(response); //6、登录失败
return false;
}
return true;
}
//登录失败时默认返回401状态码
private void onLoginFail(ServletResponse response) throws IOException {
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
httpResponse.getWriter().write("login error");
}
}
public class StatelessToken implements AuthenticationToken {
private String username;
private Map<String, ?> params;
private String clientDigest;
//省略部分代码
public Object getPrincipal() { return username;}
public Object getCredentials() { return clientDigest;}
}
public class StatelessRealm extends AuthorizingRealm {
public boolean supports(AuthenticationToken token) {
//仅支持StatelessToken类型的Token
return token instanceof StatelessToken;
}
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//根据用户名查找角色,请根据需求实现
String username = (String) principals.getPrimaryPrincipal();
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
authorizationInfo.addRole("admin");
return authorizationInfo;
}
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
StatelessToken statelessToken = (StatelessToken) token;
String username = statelessToken.getUsername();
String key = getKey(username);//根据用户名获取密钥(和客户端的一样)
//在服务器端生成客户端参数消息摘要
String serverDigest = HmacSHA256Utils.digest(key, statelessToken.getParams());
//然后进行客户端消息摘要和服务器端消息摘要的匹配
return new SimpleAuthenticationInfo(
username,
serverDigest,
getName());
}
private String getKey(String username) {//得到密钥,此处硬编码一个
if("admin".equals(username)) {
return "dadadswdewq2ewdwqdwadsadasd";
}
return null;
}
}
<!-- Realm实现 --> <bean id="statelessRealm" class="com.github.zhangkaitao.shiro.chapter20.realm.StatelessRealm"> <property name="cachingEnabled" value="false"/> </bean> <!-- Subject工厂 --> <bean id="subjectFactory" class="com.github.zhangkaitao.shiro.chapter20.mgt.StatelessDefaultSubjectFactory"/> <!-- 会话管理器 --> <bean id="sessionManager" class="org.apache.shiro.session.mgt.DefaultSessionManager"> <property name="sessionValidationSchedulerEnabled" value="false"/> </bean> <!-- 安全管理器 --> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="statelessRealm"/> <property name="subjectDAO.sessionStorageEvaluator.sessionStorageEnabled" value="false"/> <property name="subjectFactory" ref="subjectFactory"/> <property name="sessionManager" ref="sessionManager"/> </bean> <!-- 相当于调用SecurityUtils.setSecurityManager(securityManager) --> <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> <property name="staticMethod" value="org.apache.shiro.SecurityUtils.setSecurityManager"/> <property name="arguments" ref="securityManager"/> </bean>
<bean id="statelessAuthcFilter" class="com.github.zhangkaitao.shiro.chapter20.filter.StatelessAuthcFilter"/>
<!-- Shiro的Web过滤器 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager"/>
<property name="filters">
<util:map>
<entry key="statelessAuthc" value-ref="statelessAuthcFilter"/>
</util:map>
</property>
<property name="filterChainDefinitions">
<value>
/**=statelessAuthc
</value>
</property>
</bean>
public class ClientTest {
private static Server server;
private RestTemplate restTemplate = new RestTemplate();
@BeforeClass
public static void beforeClass() throws Exception {
//创建一个server
server = new Server(8080);
WebAppContext context = new WebAppContext();
String webapp = "shiro-example-chapter20/src/main/webapp";
context.setDescriptor(webapp + "/WEB-INF/web.xml"); //指定web.xml配置文件
context.setResourceBase(webapp); //指定webapp目录
context.setContextPath("/");
context.setParentLoaderPriority(true);
server.setHandler(context);
server.start();
}
@AfterClass
public static void afterClass() throws Exception {
server.stop(); //当测试结束时停止服务器
}
}
@Test
public void testServiceHelloSuccess() {
String username = "admin";
String param11 = "param11";
String param12 = "param12";
String param2 = "param2";
String key = "dadadswdewq2ewdwqdwadsadasd";
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
params.add(Constants.PARAM_USERNAME, username);
params.add("param1", param11);
params.add("param1", param12);
params.add("param2", param2);
params.add(Constants.PARAM_DIGEST, HmacSHA256Utils.digest(key, params));
String url = UriComponentsBuilder
.fromHttpUrl("http://localhost:8080/hello")
.queryParams(params).build().toUriString();
ResponseEntity responseEntity = restTemplate.getForEntity(url, String.class);
Assert.assertEquals("hello" + param11 + param12 + param2, responseEntity.getBody());
}
@Test
public void testServiceHelloFail() {
String username = "admin";
String param11 = "param11";
String param12 = "param12";
String param2 = "param2";
String key = "dadadswdewq2ewdwqdwadsadasd";
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
params.add(Constants.PARAM_USERNAME, username);
params.add("param1", param11);
params.add("param1", param12);
params.add("param2", param2);
params.add(Constants.PARAM_DIGEST, HmacSHA256Utils.digest(key, params));
params.set("param2", param2 + "1");
String url = UriComponentsBuilder
.fromHttpUrl("http://localhost:8080/hello")
.queryParams(params).build().toUriString();
try {
ResponseEntity responseEntity = restTemplate.getForEntity(url, String.class);
} catch (HttpClientErrorException e) {
Assert.assertEquals(HttpStatus.UNAUTHORIZED, e.getStatusCode());
Assert.assertEquals("login error", e.getResponseBodyAsString());
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有