Я использую Apache Shiro для своего веб-приложения, и у меня возникают проблемы с его работой по назначению.Apache Shiro + Проблемы с аутентификацией
Что мне нужно, это часть авторизации Shiro Framework, но я не могу следовать ни одному из этих руководств, поскольку они все разные, и я просто не могу заставить его работать в моем приложении.
Вот что я хочу использовать Shiro рамочную:
- определить существующий login.jsp как мой логин-страницу
- определить * .jsp страницу, которая отображается при попытке Войти был удаленный
- , когда логин не был успешным, пользователь остается в login.jsp, но отображается сообщение об ошибке о его неудачной попытке входа в систему
- все другие * .jsp страницы exect login.jsp не должны быть доступны, когда пользователь не зарегистрирован в
Сейчас мое приложение делает это следующим образом:
- форму входа
action
параметр Кальес login.java (сервлет) - на преуспевающим входе -> страница portal.jsp отображается
- в страница .../portal.jsp можно вызвать без входа в систему -> Это не должно быть возможным в окончательной версии моей заявки
следующие вещи, которые я выяснил далеко:
shiro.ini:
[main]
# define login page
authc.loginUrl = /SSP/login.jsp
# name of request parameter with username;
authc.usernameParam = username
# name of request parameter with password;
authc.passwordParam = password
# redirect after successful login
authc.successUrl = /SSP/portal.jsp
[urls]
# enable authc filter for all application pages
/SSP/**=authc
сиро часть моей web.xml выглядит следующим образом:
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<listener>
<listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class>
</listener>
<filter>
<filter-name>ShiroFilter</filter-name>
<filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ShiroFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
<dispatcher>INCLUDE</dispatcher>
<dispatcher>ERROR</dispatcher>
</filter-mapping>
сиро часть моего pom.xml:
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.2.4</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>1.2.4</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.2.4</version>
</dependency>
Ошибка, которую я получаю:
java.lang.IllegalArgumentException: Configuration error.
Specified object [authc] with property [loginUrl] without first defining that object's class.
Please first specify the class property first, e.g. myObject = fully_qualified_class_name and then define additional properties.
EDIT:
Кажется, эта линия в shiro.ini сделал трюк:
authc = org.apache.shiro.web.filter.authc.PassThruAuthenticationFilter
Но теперь у меня есть проблема, что приложение не использует свой собственный класс логин
login.java:
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String url = "/login.jsp";
// Get Login credentials from Login form
username = request.getParameter("username");
password = request.getParameter("password");
//SecurityManager securityManager = Startup.getSecurityManager();
//2. Get the current Subject:
Subject currentUser = SecurityUtils.getSubject();
//3. Login:
if (!currentUser.isAuthenticated()) {
// create UsernamePasswordToken
UsernamePasswordToken token = new UsernamePasswordToken("cn=" + username + ",ou=People,dc=maxcrc,dc=com", password);
try {
currentUser.login(token);
token.clear();
url = "/portal.jsp";
System.out.println("User [" + currentUser.getPrincipal() +"] logged succesfully");
//4. Create User Session
Session session = currentUser.getSession();
// get user_id
user_id = get_users_id(username);
// create new object of User class
User new_user = new User(user_id, username);
// Set HTTP Session Parameters
session.setAttribute("user", username);
session.setAttribute("user_id", user_id);
session.setAttribute("obj_user", new_user);
session.setAttribute("currentUser", currentUser);
} catch (UnknownAccountException uae) {
System.out.println("There is no user with username of " + token.getPrincipal());
} catch (IncorrectCredentialsException ice) {
System.out.println("Password for account " + token.getPrincipal() + " was incorrect!");
} catch (LockedAccountException lae) {
System.out.println("The account for username " + token.getPrincipal() + " is locked. " + "Please contact your administrator to unlock it.");
}
// ... catch more exceptions here (maybe custom ones specific to your application?
catch (AuthenticationException ae) {
System.out.println("ERROR: " + ae);
}
// Done, redirect User to applications main page
request.getRequestDispatcher(url).forward(request, response);
}
}
Как могу ли я использовать свой собственный класс (см. вышеприведенный фрагмент login.java) для аутентификации?
EDIT END
Может кто-нибудь привести пример о том, как:
- включить авторизацию
- включить перенаправление страницы после попытки успешного входа в систему
- дают возможность остаться на странице входа, но изображающий сообщение об ошибке после неудачной попытки входа
- сделать все остальные страницы o е приложения только доступной, если пользователь вошел в систему