NutzCN Logo
问答 shiro的集成问题
发布于 3009天前 作者 老司机 3291 次浏览 复制 上一个帖子 下一个帖子
标签:

集成shiro后登陆方法还是在usermodel里面

 @At
    @Filters // 覆盖UserModule类的@Filter设置,因为登陆可不能要求是个已经登陆的Session
    @POST
    public Object login(@Param("username")String username, 
            @Param("password")String password, 
            @Param("captcha")String captcha,
            @Attr(scope=Scope.SESSION, value="nutz_captcha")String _captcha,
            HttpSession session) {
        NutMap re = new NutMap();
        if (!Toolkit.checkCaptcha(_captcha, captcha)) {
            return re.setv("ok", false).setv("msg", "验证码错误");
        }
        int userId = userService.fetch(username, password);
        if (userId < 0) {
            return re.setv("ok", false).setv("msg", "用户名或密码错误");
        } else {
            session.setAttribute("me", userId);
            return re.setv("ok", true);
        }
    }

只是把session换成了shiro的session,可是shiro怎么知道attr里的me就是用户呢?而且之往里面塞了一个id而已
NutDaoRealm 里的doGetAuthenticationInfo里的upToken.getUsername()是怎么来的呢,而且因为nutz我才开始知道shiro所以对整个流程还不是很清楚,望讲解

11 回复

看shiro插件的说明

来自炫酷的 NutzCN

PS: shiro是个大坑, 慎入

@wendal Readme说继承AbstractNutRealm,实现一个Realm,但是没有看到AbstractNutRealm这个类啊?在哪下的?

@wendal 集成后能登录,但是登录后向requireuser跳,直接跳到/user/login,而且在nutzdaorealm里打断点,根本不停,why????
usermodule:

	@At
	@RequiresUser
	public int count() {
		return dao.count(User.class);
	}

	@At
	@Filters // 覆盖UserModule类的@Filter设置,因为登陆可不能要求是个已经登陆的Session
	@POST
	public Object login(@Param("username") String username, @Param("password") String password,
			// @Param("captcha") String captcha, @Attr(scope = Scope.SESSION,
			// value = "nutz_captcha") String _captcha,
			HttpSession session) {
		NutMap re = new NutMap();
		int userId = userService.fetch(username, password);
		if (userId < 0) {
			return re.setv("ok", false).setv("msg", "用户名或密码错误");
		} else {
			session.setAttribute("me", userId);
			return re.setv("ok", true);
		}
	}

	@GET
	@At("/login")
	@Filters
	@Ok("jsp:jsp.user.login")
	public void loginPage() {
	}
}

nutzdaorealm:

@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		// TODO Auto-generated method stub
		SimpleAuthorizationInfo auth = new SimpleAuthorizationInfo();
		return auth;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		// TODO Auto-generated method stub
		CaptchaUsernamePasswordToken uptoken = (CaptchaUsernamePasswordToken) token;
		User user = dao.fetch(User.class, Cnd.where("name", "=", uptoken.getUsername()));
		if (user == null) {
			return null;
		}
		if (user.isLocked()) {
			throw new LockedAccountException("Account [" + uptoken.getUsername() + "] is locked.");
		}
		SimpleAccount account = new SimpleAccount(user.getId(), user.getName(), getName());
		account.setCredentialsSalt(ByteSource.Util.bytes(user.getSalt()));
		return account;
	}

shiro.ini:

[main]
sha256Matcher = org.apache.shiro.authc.credential.Sha256CredentialsMatcher
nutzdao_realm = net.wendal.nutzbook.shiro.realm.NutDaoRealm
nutzdao_realm.credentialsMatcher = $sha256Matcher

authc = org.nutz.integration.shiro.CaptchaFormAuthenticationFilter
authc.loginUrl  = /user/login
logout.redirectUrl= /user/login

[urls]
/rs/*        = anon
/user/logout = logout
/user/error  = anon
/user/profile/active/mail = anon
/user/**     = authc

@wendal 为了方便,没写role和Permission

要完成shiro的登录流程,而不是简单在session里面放个值的

Subject subject = SecurityUtils.getSubject();
subject.login(new SimpleShiroToken(user.getId()));

@wendal 在usemodule里增加了

Subject subject = SecurityUtils.getSubject();
subject.login(new SimpleShiroToken(user.getId()));

SimpleShiroToken照搬的

https://github.com/nutzam/nutzmore/blob/master/nutz-integration-shiro/src/main/java/org/nutz/integration/shiro/SimpleShiroToken.java

结果报错,报错如下:

2016-09-27 11:26:42,092 org.apache.shiro.web.servlet.SimpleCookie.addCookieHeader(SimpleCookie.java:226) DEBUG - Added HttpServletResponse Cookie [rememberMe=deleteMe; Path=/nutzbook; Max-Age=0; Expires=Mon, 26-Sep-2016 03:26:42 GMT]
2016-09-27 11:26:42,093 org.nutz.mvc.impl.processor.FailProcessor.process(FailProcessor.java:28) WARN  - Error@/user/login :
org.apache.shiro.authc.pam.UnsupportedTokenException: Realm [net.wendal.nutzbook.shiro.realm.NutDaoRealm@3d842c04] does not support authentication token [net.wendal.nutzbook.shiro.SimpleShiroToken@268934b0].  Please ensure that the appropriate Realm implementation is configured correctly or that the realm accepts AuthenticationTokens of this type.
	at org.apache.shiro.authc.pam.ModularRealmAuthenticator.doSingleRealmAuthentication(ModularRealmAuthenticator.java:178)
	at org.apache.shiro.authc.pam.ModularRealmAuthenticator.doAuthenticate(ModularRealmAuthenticator.java:267)
	at org.apache.shiro.authc.AbstractAuthenticator.authenticate(AbstractAuthenticator.java:198)
	at org.apache.shiro.mgt.AuthenticatingSecurityManager.authenticate(AuthenticatingSecurityManager.java:106)
	at org.apache.shiro.mgt.DefaultSecurityManager.login(DefaultSecurityManager.java:270)
	at org.apache.shiro.subject.support.DelegatingSubject.login(DelegatingSubject.java:256)
	at net.wendal.nutzbook.module.UserModule.login(UserModule.java:55)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
	at java.lang.reflect.Method.invoke(Unknown Source)
	at org.nutz.mvc.impl.processor.MethodInvokeProcessor.process(MethodInvokeProcessor.java:25)
	at org.nutz.mvc.impl.processor.AbstractProcessor.doNext(AbstractProcessor.java:44)
	at org.nutz.mvc.impl.processor.AdaptorProcessor.process(AdaptorProcessor.java:33)
	at org.nutz.mvc.impl.processor.AbstractProcessor.doNext(AbstractProcessor.java:44)
	at org.nutz.mvc.impl.processor.ActionFiltersProcessor.process(ActionFiltersProcessor.java:58)
	at org.nutz.mvc.impl.processor.AbstractProcessor.doNext(AbstractProcessor.java:44)
	at org.nutz.integration.shiro.NutShiroProcessor.process(NutShiroProcessor.java:51)
	at org.nutz.mvc.impl.processor.AbstractProcessor.doNext(AbstractProcessor.java:44)
	at org.nutz.mvc.impl.processor.ModuleProcessor.process(ModuleProcessor.java:123)
	at org.nutz.mvc.impl.processor.AbstractProcessor.doNext(AbstractProcessor.java:44)
	at org.nutz.mvc.impl.processor.EncodingProcessor.process(EncodingProcessor.java:27)
	at org.nutz.mvc.impl.processor.AbstractProcessor.doNext(AbstractProcessor.java:44)
	at org.nutz.mvc.impl.processor.UpdateRequestAttributesProcessor.process(UpdateRequestAttributesProcessor.java:15)
	at org.nutz.mvc.impl.NutActionChain.doChain(NutActionChain.java:44)
	at org.nutz.mvc.impl.ActionInvoker.invoke(ActionInvoker.java:67)
	at org.nutz.mvc.ActionHandler.handle(ActionHandler.java:31)
	at org.nutz.mvc.NutFilter.doFilter(NutFilter.java:198)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
	at org.apache.shiro.web.servlet.ProxiedFilterChain.doFilter(ProxiedFilterChain.java:61)
	at org.apache.shiro.web.servlet.AdviceFilter.executeChain(AdviceFilter.java:108)
	at org.apache.shiro.web.servlet.AdviceFilter.doFilterInternal(AdviceFilter.java:137)
	at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)
	at org.apache.shiro.web.servlet.ProxiedFilterChain.doFilter(ProxiedFilterChain.java:66)
	at org.apache.shiro.web.servlet.AbstractShiroFilter.executeChain(AbstractShiroFilter.java:449)
	at org.apache.shiro.web.servlet.AbstractShiroFilter$1.call(AbstractShiroFilter.java:365)
	at org.apache.shiro.subject.support.SubjectCallable.doCall(SubjectCallable.java:90)
	at org.apache.shiro.subject.support.SubjectCallable.call(SubjectCallable.java:83)
	at org.apache.shiro.subject.support.DelegatingSubject.execute(DelegatingSubject.java:383)
	at org.apache.shiro.web.servlet.AbstractShiroFilter.doFilterInternal(AbstractShiroFilter.java:362)
	at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:522)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
	at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
	at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:1110)
	at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
	at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:785)
	at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1425)
	at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
	at java.lang.Thread.run(Unknown Source)

nutzdaorealm在构造方法内要注册该token类型

这token类在插件里面,不需要自己加

来自炫酷的 NutzCN

@wendal

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		// TODO Auto-generated method stub
		SimpleShiroToken upToken = (SimpleShiroToken) token;
		User user = (User) upToken.getPrincipal();
		if (user == null) {
			return null;
		}
		SimpleAccount account = new SimpleAccount(user, user.getPassword(), getName());
		account.setCredentialsSalt(ByteSource.Util.bytes(user.getSalt()));
		return account;
	}

在最后return的时候报空指针?

2016-09-27 13:48:59,333 org.apache.shiro.realm.AuthenticatingRealm.getAuthenticationInfo(AuthenticatingRealm.java:569) DEBUG - Looked up AuthenticationInfo [net.wendal.nutzbook.bean.User@33243363] from doGetAuthenticationInfo
2016-09-27 13:48:59,334 org.apache.shiro.realm.AuthenticatingRealm.cacheAuthenticationInfoIfPossible(AuthenticatingRealm.java:507) DEBUG - AuthenticationInfo caching is disabled for info [net.wendal.nutzbook.bean.User@33243363].  Submitted token: [org.nutz.integration.shiro.SimpleShiroToken@7e3ea041].
2016-09-27 13:48:59,340 org.apache.shiro.authc.AbstractAuthenticator.authenticate(AbstractAuthenticator.java:216) WARN  - Authentication failed for token submission [org.nutz.integration.shiro.SimpleShiroToken@7e3ea041].  Possible unexpected error? (Typical or expected login exceptions should extend from AuthenticationException).
java.lang.NullPointerException

@qq_c1bab051 看nutzcn现成的实现.

来自炫酷的 NutzCN

添加回复
请先登陆
回到顶部