在wso2中获取用户的角色

时间:2015-04-11 02:04:24

标签: java jsp wso2

我已经使用wso2im创建了用户并为他们分配了不同的角色。使用这些我设法限制对.jsp文件的访问,因此角色似乎正常工作。

问题在于我需要在同一个JSP中向不同的角色显示不同的东西(例如,角色AAA可以执行xxx和yyy,角色BBB可以执行zzz),我尝试使用角色检查角色request.isUserInRole(" role")但是当从.jsp本身和处理身份验证的servlet尝试时,它总是返回null。

1 个答案:

答案 0 :(得分:0)

最后设法让它发挥作用。获取servlet的角色并将其存储在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 {
	
	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");
		        
        try {
			if(authenticate(user,pwd)){
				HttpSession session = request.getSession();
			    session.setAttribute("user", user);
			    //setting session to expiry in 30 mins
			    session.setMaxInactiveInterval(30*60);
			    Cookie userName = new Cookie("user", user);
			    userName.setMaxAge(30*60);
				
				String[] roles = getRoleListOfUser(user);
				String rolesTodos = null;
				for (String s: roles){
					if (!s.equals("Internal/everyone")) {
						if (rolesTodos == null){
							rolesTodos = s;
						} else {
							//System.out.println("Rol: " + s);
							rolesTodos = rolesTodos + "," + s;
						}
					}
				}
				
				//System.out.println("Roles: " + rolesTodos);
			    Cookie rolesCookie = new Cookie("roles", rolesTodos);
				rolesCookie.setMaxAge(30*60);
								
			    response.addCookie(userName);
			    response.addCookie(rolesCookie);
			    response.sendRedirect("index.jsp");
			}else{
			    RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
			    PrintWriter out= response.getWriter();
			    out.println("<font color=red>Either user name or password is wrong.</font>");
			    rd.include(request, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
 
    }
    
    private boolean authenticate(String userName, Object credential) throws Exception {
        if (!(credential instanceof String)) {
            throw new Exception("Unsupported type of password");
        }
        try {
        	if(stub == null) {
        	    stub = new RemoteUserStoreManagerServiceStub(null, serverUrl
        	            + "RemoteUserStoreManagerService");
        	    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);

        	}
            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;
    }
}