2015-04-11 4 views
0

Я создал пользователей и назначил им разные роли, используя wso2im. Используя их, мне удалось ограничить доступ к файлу .jsp, так что роли, похоже, работают правильно.Получение ролей пользователя в wso2

Проблема заключается в том, что мне нужно отображать разные вещи для разных ролей в одном JSP (например, роль AAA может выполнять xxx и yyy, роль BBB может выполнять zzz), я пытаюсь проверить роли, используя запрос .isUserInRole ("role"), но он всегда возвращает null, как при попытке выполнить сам .jsp, так и сервлет, который обрабатывает аутентификацию.

ответ

0

Наконец-то удалось заставить его работать. Получение ролей с сервлетом и сохранение их в файле cookie. Ни в безопасности и не очень, но не делает работу:

package foo; 
 

 
import java.io.IOException; 
 

 
import javax.servlet.ServletException; 
 
import javax.servlet.annotation.WebServlet; 
 
import javax.servlet.http.HttpServlet; 
 
import javax.servlet.http.HttpServletRequest; 
 
import javax.servlet.http.HttpServletResponse; 
 

 
import java.io.PrintWriter; 
 

 
import javax.servlet.RequestDispatcher; 
 
import javax.servlet.http.Cookie; 
 
import javax.servlet.http.HttpSession; 
 

 
import org.apache.axis2.transport.http.HttpTransportProperties; 
 
import org.apache.axis2.client.Options; 
 
import org.apache.axis2.transport.http.HTTPConstants; 
 

 
import org.wso2.carbon.um.ws.api.stub.RemoteUserStoreManagerServiceStub; 
 

 
/** 
 
* Servlet implementation class LoginServlet 
 
*/ 
 
@WebServlet("/LoginServlet") 
 
public class LoginServlet extends HttpServlet { 
 
\t 
 
\t private static final long serialVersionUID = 1L; 
 
    private final String basicAuthUserID = "admin"; 
 
    private final String basicAuthPassword = "admin"; 
 
    private final String serverUrl = "https://localhost:9444/services/"; 
 
    private RemoteUserStoreManagerServiceStub stub = null; 
 

 

 
    
 
    protected void doPost(HttpServletRequest request, 
 
      HttpServletResponse response) throws ServletException, IOException { 
 
    
 
     // get request parameters for userID and password 
 
     String user = request.getParameter("user"); 
 
     String pwd = request.getParameter("pwd"); 
 
\t \t   
 
     try { 
 
\t \t \t if(authenticate(user,pwd)){ 
 
\t \t \t \t HttpSession session = request.getSession(); 
 
\t \t \t  session.setAttribute("user", user); 
 
\t \t \t  //setting session to expiry in 30 mins 
 
\t \t \t  session.setMaxInactiveInterval(30*60); 
 
\t \t \t  Cookie userName = new Cookie("user", user); 
 
\t \t \t  userName.setMaxAge(30*60); 
 
\t \t \t \t 
 
\t \t \t \t String[] roles = getRoleListOfUser(user); 
 
\t \t \t \t String rolesTodos = null; 
 
\t \t \t \t for (String s: roles){ 
 
\t \t \t \t \t if (!s.equals("Internal/everyone")) { 
 
\t \t \t \t \t \t if (rolesTodos == null){ 
 
\t \t \t \t \t \t \t rolesTodos = s; 
 
\t \t \t \t \t \t } else { 
 
\t \t \t \t \t \t \t //System.out.println("Rol: " + s); 
 
\t \t \t \t \t \t \t rolesTodos = rolesTodos + "," + s; 
 
\t \t \t \t \t \t } 
 
\t \t \t \t \t } 
 
\t \t \t \t } 
 
\t \t \t \t 
 
\t \t \t \t //System.out.println("Roles: " + rolesTodos); 
 
\t \t \t  Cookie rolesCookie = new Cookie("roles", rolesTodos); 
 
\t \t \t \t rolesCookie.setMaxAge(30*60); 
 
\t \t \t \t \t \t \t \t 
 
\t \t \t  response.addCookie(userName); 
 
\t \t \t  response.addCookie(rolesCookie); 
 
\t \t \t  response.sendRedirect("index.jsp"); 
 
\t \t \t }else{ 
 
\t \t \t  RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html"); 
 
\t \t \t  PrintWriter out= response.getWriter(); 
 
\t \t \t  out.println("<font color=red>Either user name or password is wrong.</font>"); 
 
\t \t \t  rd.include(request, response); 
 
\t \t \t } 
 
\t \t } catch (Exception e) { 
 
\t \t \t e.printStackTrace(); 
 
\t \t } 
 
    
 
    } 
 
    
 
    private boolean authenticate(String userName, Object credential) throws Exception { 
 
     if (!(credential instanceof String)) { 
 
      throw new Exception("Unsupported type of password"); 
 
     } 
 
     try { 
 
     \t if(stub == null) { 
 
     \t  stub = new RemoteUserStoreManagerServiceStub(null, serverUrl 
 
     \t    + "RemoteUserStoreManagerService"); 
 
     \t  HttpTransportProperties.Authenticator basicAuth = new HttpTransportProperties.Authenticator(); 
 
       basicAuth.setUsername(basicAuthUserID); 
 
       basicAuth.setPassword(basicAuthPassword); 
 
       basicAuth.setPreemptiveAuthentication(true); 
 

 
       final Options clientOptions = stub._getServiceClient().getOptions(); 
 
       clientOptions.setProperty(HTTPConstants.AUTHENTICATE, basicAuth); 
 
       stub._getServiceClient().setOptions(clientOptions); 
 

 
     \t } 
 
      return stub.authenticate(userName, (String) credential); 
 
     } catch (Exception e) { 
 
      handleException(e.getMessage(), e); 
 
     } 
 
     return false; 
 
    } 
 
    
 
    
 
    private String[] handleException(String msg, Exception e) throws Exception { 
 
     System.out.println(e.getMessage() + e); 
 
     throw new Exception(msg, e); 
 
    } 
 
    
 
    public String[] getRoleListOfUser(String userName) throws Exception { 
 
     try { 
 
      return stub.getRoleListOfUser(userName); 
 
     } catch (Exception e) { 
 
      System.out.println(e.getMessage() + e); 
 
     } 
 
     return null; 
 
    } 
 
}

Смежные вопросы