Login Navigation Handler

Hello,
I would like to implement a navigation handler to control access to some pages, in the sense that if the user is not logged in, he/she cannot access some pages.
So let's say the user is not logged in, clicks on some menu link, gets redirected to the login page, logs in, and then is redirected to the page he wanted to access.
I can't manage to figure out how to do the last part.
My navigation handler:
public class LoginNavigationHandler extends NavigationHandler {
     NavigationHandler _base;
     String actionNameCurrent;
     String actionMethodCurrent;
     public LoginNavigationHandler (NavigationHandler base) {
          super();
          _base = base;     
     public void handleNavigation(FacesContext fc, String actionMethod, String actionName) {
                actionNameCurrent = actionName;
                actionMethodCurrent = actionMethod;
                HttpSession session = (HttpSession)fc.getExternalContext().getSession(false);
                LoginBean  loginManager = (LoginBean)session.getAttribute(LoginBean.BEAN_MAPPING);
                if (loginManager == null){
                     loginManager = new LoginBean();
                     loginManager.setLoggedIn(false);
                     session.setAttribute(LoginBean.BEAN_MAPPING, loginManager);
                if (actionNameCurrent!=null) {
                     if (actionNameCurrent.equals(PageEnum.NAV_PAGE_RETURN_BACK)) {
                          navigationCase4ReturningBack(fc, loginManager);
                     navigationCase4Login(fc, loginManager);
                _base.handleNavigation(fc, actionMethodCurrent, actionNameCurrent);
     private void navigationCase4Login(FacesContext fc, LoginBean loginManager) {
          //if not logged in and not navigating to login page
          if (!loginManager.isLoggedIn() &&
                   !actionNameCurrent.equals(PageEnum.NAV_PAGE_LOGIN)) {
               //store the current navigation position
               loginManager.setPreviousAction(actionNameCurrent);
               loginManager.setPreviousMethod(actionMethodCurrent);
               loginManager.setPreviousViewId(fc.getViewRoot().getViewId());                    
               System.out.println("Set previous action name "+actionNameCurrent);          
               //if not navigating to one of the publicly available pages
               if (!actionNameCurrent.equals(PageEnum.NAV_PAGE_PRODUCTSLIST)
                      && !actionNameCurrent.equals(PageEnum.NAV_PAGE_REGISTER)                    
                      && !actionNameCurrent.equals(PageEnum.NAV_PAGE_CONTACT)){
                    //redirect to login page
                    actionNameCurrent = PageEnum.NAV_PAGE_LOGIN;                    
     private void navigationCase4ReturningBack(FacesContext fc, LoginBean loginManager) {
          if (loginManager.isLoggedIn()) {
               //restore the previous navigation position                
               actionNameCurrent = loginManager.getPreviousAction();
               actionMethodCurrent = loginManager.getPreviousMethod();
               fc.getViewRoot().setViewId(loginManager.getPreviousViewId());                
}I have a menu, each menu item has an action (method is called 'init' but I also have some items with actionListeners associated to them).
What happens is this: onclick, the action/actionListener method is called, then the navigation handler gets called. I'd like to invert the order, because I need the user's data before loading page content. Any way to do this?
I've tried parsing the actionMethod string to get the bean name and invoke init method by reflection, but in the case of the menu items with actionlisteners it does not work :(
Thanks.

I've solved the problem:
private void navigationCase4ReturningBack(FacesContext fc, LoginBean loginManager) {
     if (loginManager.isLoggedIn()) {
          //restore the previous navigation position                
          actionNameCurrent = loginManager.getPreviousAction();
          actionMethodCurrent = loginManager.getPreviousMethod();
          fc.getViewRoot().setViewId(loginManager.getPreviousViewId());
          try{
               if (actionMethodCurrent != null && !actionMethodCurrent.isEmpty()){
                       ELContext elContext = fc.getELContext();
                     ExpressionFactory ef = fc.getApplication().getExpressionFactory();
                     MethodExpression me = ef.createMethodExpression(elContext, actionMethodCurrent, String.class, new Class[] {});
                     me.invoke(elContext, null);
           }catch(Exception e){
               e.printStackTrace();
     }

Similar Messages

  • Authentication Challenge/Hotspot login cannot handle this page ...

    I appears that the HotSpot login cannot handle the login pop-up window of the university campus wireless. It worked well w/ OS2.x. Suggestions?

    Hello, HarryZhou. 
    Thank you for the question.  To resolve this issue, see the steps below.  This can happen as some public Wi-Fi hotspots require authentication to connect to their network via Safari.  Also, if the Wi-Fi login page is still active but the session was terminated by putting the device in sleep mode. 
    Removing or clearing stored Safari content
    To clear your history from Safari, tap Settings > Safari > Clear History
    To clear all cookies from Safari, tap Settings > Safari > Clear Cookies and Data
    iOS 5 or later: To clear other stored information from Safari, tap Advanced > Website Data > Remove All Website Data
    Once this is processed, connect to your home network and attempt to connect again. 
    Cheers,
    Jason H. 

  • Navigation Handling does not work !!!!

    hi every body
    i have two pages Login.jsp and page1.jsp, i want to prevent direct access to page1.jsp unless the user first go to login page and redirected to page1.jsp.. so if the user paste the pathe of page1.jsp immedatily , the application will redirect him to login page.
    i used the following code in pre-render method:
    FacesContext context=FacesContext.getCurrentInstance();
    Application application=context.getApplication();
    NavigationHandler navigator=application.getNavigationHandler();
    navigator.handleNavigation(context,null, "insecure");-----
    but unfortunately it does not work ,
    can any one please help me ?
    thanks in advance
    Mohammed

    Dude,
    Why not use a filter? It will save you having to add code to every page that requires a user to be logged in.
    Try http://securityfilter.sourceforge.net/ for something comprehensive. Or if you just want something that just intercepts a request and checks if a user is logged in (e.g. if the username property in SessionBean1 is set) and redirects the user to the login page if not... it's pretty easy if you've worked with filters before.
    Try it out and ask again if you want pointers.
    Cheers,
    Dave

  • Navigation Handler is not working in jspx page..

    Hi,
    I have written a sample application with 3 pages.
    - one.jpsx
    - two.jspx
    - error.jspx
    In one.jspx page a scriptlet is written to forward the page to error.jspx. But it is not working. Any help or suggestions would be appreciated.
    pages:
    one.jspx_
    <?xml version='1.0' encoding='windows-1252'?>
    <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:af="http://xmlns.oracle.com/adf/faces/rich">
    <jsp:directive.page contentType="text/html;charset=windows-1252"/>
    <jsp:directive.page import="javax.faces.context.FacesContext"/>
    <jsp:scriptlet>
    FacesContext fc = FacesContext.getCurrentInstance();
         fc.getApplication().getNavigationHandler().handleNavigation(fc,"","error");
    </jsp:scriptlet>
    <f:view>
    <af:document>
    <af:form>
    <af:outputText value="This is first page"/>
    <af:commandButton text="Click on" action="two"/>
    </af:form>
    </af:document>
    </f:view>
    </jsp:root>
    error.jspx_
    <?xml version='1.0' encoding='windows-1252'?>
    <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:af="http://xmlns.oracle.com/adf/faces/rich">
    <jsp:directive.page contentType="text/html;charset=windows-1252"/>
    <f:view>
    <af:document>
    <af:form>
    <af:outputText value="This is error page.."/>
    </af:form>
    </af:document>
    </f:view>
    </jsp:root>
    two.jspx_
    <?xml version='1.0' encoding='windows-1252'?>
    <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:af="http://xmlns.oracle.com/adf/faces/rich">
    <jsp:directive.page contentType="text/html;charset=windows-1252"/>
    <f:view>
    <af:document>
    <af:form>
    <af:outputText value="This is second page"/>
    </af:form>
    </af:document>
    </f:view>
    </jsp:root>
    adfc-config.xml_
    <?xml version="1.0" encoding="windows-1252" ?>
    <adfc-config xmlns="http://xmlns.oracle.com/adf/controller" version="1.2">
    <view id="one">
    <page>/one.jspx</page>
    </view>
    <view id="two">
    <page>/two.jspx</page>
    </view>
    <view id="error">
    <page>/error.jspx</page>
    </view>
    <control-flow-rule>
    <from-activity-id>one</from-activity-id>
    <control-flow-case>
    <from-outcome>two</from-outcome>
    <to-activity-id>two</to-activity-id>
    </control-flow-case>
    </control-flow-rule>
    </adfc-config>
    Thanks
    Sukumar

    What's the reason you think the JSP <jsp:scriptlet> tags works in JSF?
    CM.

  • [Create Login] Provisioning Error: event handler/adapter could not be found

    Hello,
    I am running a fresh install of OIM 9.0.3 (installed yesterday) on a Windows XP Machine running:
    Weblogic 813 SP6
    JDK142 11,
    MSSQL 2000 SP3a I have a test resource, a simple MSSQL Table with a few fields, which I used the connector pack to install and connect. I imported the resource without any issues. However, when I attempt to Create Login on the resource, it gives me the following error:
    "An error occurred while retrying one of the tasks
    Create Login: Event Handler not found"When I check the details of Create Login (in my To-Do List for xelsysadm):
    Error Details
    The class file for event handler/adapter "adpDBCREATELOGIN" could not be found.I am very new to this system, and I really don't know where to begin trouble shooting this issue. Any ideas on what might be wrong with the system? It could be anywhere from missing a step in the beginning of the installation to doing something incorrectly. Any pointers on where I can start troubleshooting as to why I can't provision would be very helpful and much appreciated!
    Thanks

    Did you compile the adapters? When you import them from XML they must be compiled before you can use them. Go to the Design Console -> Dev tools -> Adapter Manager and compile them there.

  • Navigation handlers and user authentication

    I've implemented a system to force user logins based on the code demonstrated here: http://www.jsftutorials.net/jsfNavigation/jsf-login-navigation-redirect.html but I've come across a problem.
    It seems the navigation handler is called only when JSF needs to resolve the outcome of an action and this means that in certain cases a user can view a secure page without having to log in. For example, using the example app from the above link, if a user goes to the start page of the project and clicks on the command buttons to access the protected pages, they are re-directed to the login page as expected. However, if they go to the url of the protected page directly (eg http://localhost:8080/jsf-loginRedirect/secure/editUserProfile.jsf ) it still displays the page.
    Currently I've got a filter in place that re-directs the user to the login page of the web app if there isn't a valid user logged in, but as this runs outside a Faces context I can't track the user's requests.
    Is there some way I can force JSF to call the navigation handler for normal get requests?

    Chops,
    There are 2 things related to this issue,
    1. When the user goes out of the application, you must invalidate the session. So that the userid will not be present in the session.
    2. You can have a phase listener that checks for User Id in session, if the user id is empty, you can re-direct the user to login page. If user id is present automatically the control will go to the navigation rule page.
    Phase Listener will enforce the user authentication.
    Hope this logic helps you to solve the issue.
    Thanks
    Prakash

  • Navigation and Creating  a navigation rule at runtime

    Hi all,
    How can I create a navigation rule at runtime?
    I got all my pages (names and locations) stored in a database table.All my pages are jspx format.
    I don't want to create navigation rules for each page, Instead I want to use the location stored in the database and create a navigation rule to navigate to.
    I tried navigating using ServletRequest :
            ExternalContext ectx = FacesContext.getCurrentInstance().getExternalContext();
            HttpServletResponse response = (HttpServletResponse)ectx.getResponse();
            HttpServletRequest  request = (HttpServletRequest)ectx.getRequest();
            request.getRequestDispatcher("/faces/Titles.jspx").forward(request,response);But it blows after the first call.
    is it possible to create a navigation rule in a Bean or is there another way to call jspx pages from a Bean without loosing the session.
    Can someone help me please.
    thanks in advance,
    Ahmad Esbita

    Ahmad,
    I don't know of any way to programatically create navigation cases at runtime. However, perhaps you could try creating a NavigationHandler decorator. Let's assume you have a function called "getViewIDforAction" that does the database lookup and returns the view ID for a given action code. You could do something like this:
    package my.code;
    import javax.faces.application.NavigationHandler;
    import javax.faces.context.FacesContext;
    public class MyNavigationManager extends NavigationHandler
       NavigationHandler _base;
       public NavigationManager (NavigationHandler base)
          super();
          _base = base;
       public void handleNavigation(FacesContext fc, String actionMethod, String actionName)
          String viewID = getViewIDforAction(actionName);
          if (viewID != null && ! "".equals(viewID))
             fc.getViewRoot().setViewId(viewID);
          else
             _base.handleNavigation(fc, actionMethod, actionName);
    }You'll also need this in faces-config.xml:
    <application>
      <navigation-handler>my.code.MyNavigationManager</navigation-handler>
    ...any other stuff...
    </application>Note: I haven't tested this or anything - just to give you an idea...
    Regards,
    john

  • Solution for all your login problems !

    Hi everyone,
    Due to the problem of designing a Login solution experienced in this forum...i have a solution that takes care of this problem i will like us all share this and pls give me a feed back as to how it works for you or its efficiency.
    This solution has three parts.
    (a) The Bean
    (b) The HTML Page
    (c) The JSP Page
    XXXXXXXXXXXXXXXXXXX The Bean XXXXXXXXXXXXXXXXXXXXX
    // dsn name is test_register
    // table name is registrationDetails
    // package bsoft;
    import java.sql.*;
    public class LoginExample {
    private String username = "";
    private String password = "";
    public LoginExample() {
    public void setUsername(String username) {
    this.username = username;
    public void setPassword(String password) {
    this.password = password;
    public boolean authenticate(String username2, String password2) {
         String query="select * from RegistrationDetails";
         String DbsUserName="";
         String DbsPassword="";
         String finalUser="";
         try {       
                   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                   Connection con=DriverManager.getConnection("jdbc:odbc:test_register", "dataDB_uname", "dataDB_pass");
                   Statement stat=con.createStatement();
                   ResultSet rst=stat.executeQuery(query);
                   while(rst.next())
                        DbsUserName=rst.getString("UserName");
                        DbsPassword=rst.getString("password");
                        if (username2.equals(DbUserName) && password2.equals(DbPassword)) {
                        break;               
                   return true;
              }catch(Exception e){
                   e.printStackTrace();
                   return false;
    XXXXXXXXXXXXXXXXXXX The HTML LOGIN PAGE XXXXXXXXXXXXXXXXXXX
    <html>
    <head>
         <title> Olumide Bolusoft </title>
    </head>
    <body>
    <br>
    <p> <h3><center>Please enter your user name and password to login to Bolusoft Inc </center></h3></p>
    <br>
    <br>
    <form action="processLogin.jsp " method = "post� >
    <center>username</center>
    <center><input type = "text" name= "username"></center>
    <center>password</center>
    <center><input type = "password" name = "password"></center>
    <center><input type="submit" name="Submit" value="Login"></center>
    </form>
    </body>
    </html>
    XXXXXXXXXXXXXXXXXX The JSP PAGE XXXXXXXXXXXXXXXXXX
    <%@ page import="java.util.*" %>
    <jsp:useBean id="bsoftLogin" class="bsoft.LoginExample"/>
    <%
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    if(bsoftLogin.authenticate(username, password) ) {
    %>
    <jsp:forward page="success.jsp"/>
         <%
    } else {
    %>
    <jsp:forward page="errorRetry.jsp"/>
    <%
    %>
    N.B name this file as processLogin.jsp
    XXXXXXXXXXXXXXX The End XXXXXXXXXXXXXXXXXXXXXXXXX
    I hope this helps majority of us who are having problems with implementing a login solution.
    Also note that u can connect to any db of ur choice..the query syntax and connection parameters now depends on that supported by your DB.
    Thanks All
    Olumide B

    Hello
    I think u have used Model 1 Architecture.
    It would be great if u follow the MVC Architecture.
    What about this??
    Login.html -> User login Page.
    Login Servlet -> Handles Request from Login.html
    LoginBean -> Uses to validate the user.
    Success.jsp/Retry.jsp -> The Final page that will be displayed.
    Am also new to Java Server Side programming.
    Suggestions are always welcome.
    Sathish

  • Restrict navigation on the basis of value

    There is a supplier table. If the status of the supplier row is DRAFT or NEW, then only will I be able to see the details of it by clicking on a commandlink. For this, I had attached a property listener to get the value #{row.Status} and then wrote the logic code in the ActionListener property of the commandlink as below.
    public void moveToDetailPageBasedOnStatus(ActionEvent actionEvent) {
            DCBindingContainer bc = (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
            Map map = bc.getParametersMap();
            String status = ((DCParameter)map.get("p_status")).getValue().toString();
            if (status.equals("DRAFT")) {
                FacesContext context = FacesContext.getCurrentInstance();
                context.getApplication().getNavigationHandler().handleNavigation(context, null, "create");
            } else {
                FacesContext context = FacesContext.getCurrentInstance();
                FacesMessage msg2 =
                    new FacesMessage(FacesMessage.SEVERITY_INFO, "", "User can see the details of an Issue in DRAFT Status only.");
                context.addMessage(null, msg2);
        }Then I read the comment by Frank Nimphius in the post below, saying that "+Why don't you use a method call activity or (even better) a router) if it is all about directing different users to different views? The approach of using HandleNavigation is not optimal+".
    FacesContext context = FacesContext.getCurrentInstance();
                context.getApplication().getNavigationHandler().handleNavigation(context, null, "create");
    http://www.adftips.com/2010/10/adf-ui-navigating-to-next-page.htmlSo then I am passing a parameter to a bounded taskflow where I am defining a pageFlowScope parameter, and then created a method call activity, set it as the default activity. The code is almost the same.
    public void checkIssueStatus() {
            String value = (String) ADFContext.getCurrent().getPageFlowScope().get("p_status");
            if ((value.equals("DRAFT")) || (value.equals("NEW"))) {
                FacesContext context = FacesContext.getCurrentInstance();
                context.getApplication().getNavigationHandler().handleNavigation(context, null, "checked");
            } else {
                FacesContext context = FacesContext.getCurrentInstance();
                FacesMessage msg2 =
                    new FacesMessage(FacesMessage.SEVERITY_INFO, "", "User can see the details of an Issue in DRAFT Status only.");
                context.addMessage(null, msg2);
        }The problem is in case the p_status is other than NEW or DRAFT, the message is getting displayed, but then detail page is also shown. I only want to display the message only and not navigate to the next page. How to resolve this issue?
    And the big question: Is my approach correct and optimal this time?

    No as you already know it the same approach you used before.
    In your task flow you use a router element as start activity wher you check the parameter using EL and depending on the outcome navigate to the view you like.
    <?xml version="1.0" encoding="UTF-8" ?>
    <adfc-config xmlns="http://xmlns.oracle.com/adf/controller" version="1.2">
      <task-flow-definition id="router-task-flow-definition">
        <default-activity>router1</default-activity>
        <router id="router1">
          <case id="__1">
            <expression>#{pageFlowScope.pStatus eq 'NEW'}</expression>
            <outcome>outcome1</outcome>
          </case>
          <case id="__2">
            <expression>#{pageFlowScope.pStatus eq 'INIT'}</expression>
            <outcome>outcome2</outcome>
          </case>
          <default-outcome>outcome3</default-outcome>
        </router>
        <view id="view1"></view>
        <view id="view2"></view>
        <view id="view3"></view>
        <control-flow-rule id="__3">
          <from-activity-id>router1</from-activity-id>
          <control-flow-case id="__4">
            <from-outcome>outcome1</from-outcome>
            <to-activity-id>view1</to-activity-id>
          </control-flow-case>
          <control-flow-case id="__5">
            <from-outcome>outcome2</from-outcome>
            <to-activity-id>view2</to-activity-id>
          </control-flow-case>
          <control-flow-case id="__6">
            <from-outcome>outcome3</from-outcome>
            <to-activity-id>view3</to-activity-id>
          </control-flow-case>
        </control-flow-rule>
        <use-page-fragments/>
      </task-flow-definition>
    </adfc-config>This way the navigation is handled by the controller without using the navigation handler.
    A full sample you can find here: http://tompeez.wordpress.com/2012/12/01/jdeveloper-11-1-1-5-0-use-router-to-create-new-row-or-edit-existing/
    Timo

  • Is it possible to  laod navigation options after querry is displayed

    Hi
    I have a question concerning the display of a query. Us ut possible to display a query and load the navigation options after the query has been displayed (in other words in the background)?
    [I am talking about the query property on how to load a query with option A, H and X]
    If yes, does it provide a relevant performance benefit in the case of using large hierarchies?
    Thx,
    Nana

    There is, but the preferred way to do something like this is through
    the action reference expression which is attached to a UCommand
    component. So you could do something like the following:
    1. set up a class which extends javax.faces.Action:
    import javax.faces.Action;
    public class RegisterAction extends Action {
    public String invoke() {
    return checkUserName();
    Set up an accessor method (javabean convention) in your business
    object bean that returns the Action instance:
    public class Register {
    public Action getRegisterAction() {
    return registerAction;
    2. set up a mapping for the Navigation Handler (assume user.jsp
    is the page where the user enters data, and welcome.jsp is
    the page that gets displayed on successful outcome). Set this up
    in your faces-config.xml:
    <navigation-rule>
    <from-tree-id>/user.jsp</from-tree-id>
    <navigation-case>
    <from-outcome>success</from-outcome>
    <to-tree-id>/welcome.jsp</to-tree-id>
    </navigation-case>
    <navigation-case>
    <from-outcome>failure</from-outcome>
    <to-tree-id>/user.jsp</to-tree-id>
    </navigation-case>
    </navigation-rule>
    Make sure that the checkUserName() method above, returns a string
    that matches the "from-outcome" element in your navigation mapping
    (in this case - "success" or "failure").
    3. attach the actionRef expression to your button component as follows
    in your jsp. Something like:
    <h:command_button commandName="register" actionRef="Register.registerAction"/>
    Hope this helps, Roger.

  • Query parameters / page navigation

    Hi,
    I have a problem which i don't know how to solve with JSF. Is it somehow possible to have a action which reacts on the first request to a page (like it is with struts actions).
    Here is my example:
    I have two JSF pages. The first page (search.jsp) has a form for searching a person with a id. The second page (show.jsp) shows the data about one person.
    There is a commandButton on search.jsp which calls a action method on my model bean. This action calls the business logic for getting the data about the person. It does either return "success" or stores a FacesMessage in the context and returns null if the id is invalid. I've set up proper navigation rules for navigating to show.jsp if the action method returns "success".
    This works fine. And now my problem... The users wants to have the possibility to set a bookmark for directly accessing the data about a person (ie. .../search.faces?id=12121). If the id is passed as query parameter, the application should behave as if he entered the data in the form. (navigate to show.jsp if the id is correct or navigate to search.jsp and display a message if the id is wrong).
    Does anybody know how to solve this problem?
    I think that the problem is that JSF actions reacts on on a user action while struts reacts on HTTP requests.
    The only way i got it working was with some javascript-code which submits the form automatically if the id is passed as query parameter (using the onLoad event of the HTML body). I would like to solve it with another way because it does not work if javascript is disabled and it looks like a hack and not like a proper solution.
    Regards,
    Matthias

    Hi,
    Thanks for your response.
    Do you have an example of your approach?
    IMHO, a Non-Faces Request does directly pass to the "Render Response" Phase (http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSFIntro10.html). Therefore, it is not possible to call the Navigation handler for for determining the next view after calling the business logic.
    Regards,
    Matthias

  • JAAS: how to login / logout programmatically?

    Dear All,
    i am writing a web application.
    i have created a JSF login form for authentication. the application use JASS mechanism for pages protection.
    i want to use the oracle's prebuild loginmodule (class name is
    "oracle.security.jazn.login.module.LDAPLoginModule") to authenticate user from LDAP server.
    to authenticate the user, my code in the backing bean for the login are:
    public String authenticate()
    MyCallbackHandler callback = new MyCallbackHandler();
    callback.setName("name");
    callback.setPassword("password");
    //create a logoncontext for specific login module, and callbackhandler
    LoginContext ctx = new LoginContext("name of configuration", callback );
    //login
    ctx.login();
    callback handler code:
    public class MyCallbackHandler implements javax.security.auth.callback.CallbackHandler
    private String name = "";
    private String password = "";
    public void setName(String name)
    this.name = name;
    public void setPassword(String password)
    this.password = password;
    public void handle(Callback[] callbacks)
    for(Callback c : callbacks)
    if (c instanceof NameCallback)
    ((NameCallback)c).setName(name);
    else if(c instanceof PasswordCallback)
    ((PasswordCallback)c).setPassword(password.toCharArray());
    the login method SEEMS succeed as no exception thrown.
    but the HttpServletRequest.getUserPrincipal() return null and whenever i visit other
    protected page (after calling the logincontext.login())...i was redirected to the login page ...
    do anyone know what the problem is??
    thanks

    Hi Frank,
    I am also facing the same problem getting the container to recognize the user using login/logout programmatically. I cannot use j_security_check as my authentication module requires three fields for authenticating the user and also I have a jsf login form.
    I have attempted the container to recognize the user by writing a filter to field all request with url-pattern "/" to get the user information from the session(saved by login action) and wrapped the request with an implementation of HttpRequestWrapper where I have overridden the methods - getRemoteUser(), getUserPrincipal(), isUserInRole().
    It is the first mapping in the web.xml and I am unable to understand if the redirect is happening before/after it reaches my AuthenticationFilter and my user is never recognized by the container since my method implementations are not called. The AuthenticationFilter is being called and I think it is something to do with the ordering of the filter-mapping. Any help would be appreciated.
    I have pasted my code below
    AuthenticationFilter
    public void doFilter(ServletRequest request, ServletResponse response,
    FilterChain fc) throws IOException, ServletException {
    if (request instanceof HttpServletRequest) {
    HttpServletRequest httpRequest = (HttpServletRequest)request;
    HttpSession session = httpRequest.getSession();
    if (session != null &&
    session.getAttribute(SESSION_ATTR_USER) != null &&
    session.getAttribute(SESSION_ATTR_ROLES) != null) {
    String username =
    (String)session.getAttribute(SESSION_ATTR_USER);
    Set roleSet = (Set)session.getAttribute(SESSION_ATTR_ROLES);
    AuthRequestWrapper wrapper =
    new AuthRequestWrapper(httpRequest, username, roleSet);
    fc.doFilter(wrapper, response);
    } else {
    fc.doFilter(request, response);
    AuthRequestWrapper
    public class AuthRequestWrapper extends HttpServletRequestWrapper {
    private String username;
    private Set roleSet;
    private Principal principal;
    public AuthRequestWrapper(HttpServletRequest request, String username,
    Set roleSet) {
    super(request);
    this.username = username;
    this.roleSet = roleSet;
    this.principal = new UserPrincipal(username);
    public String getRemoteUser() {
    return username;
    public Principal getUserPrincipal() {
    return principal;
    public boolean isUserInRole(String roleName) {
    return roleSet.contains(roleName);
    web.xml
    <filter-mapping>
    <filter-name>AuthFilter</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter-mapping>
    <filter-name>trinidad</filter-name>
    <servlet-name>Faces Servlet</servlet-name>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>REQUEST</dispatcher>
    </filter-mapping>

  • Creating navigation listener in faces config

    Hi,
    I created a class "CommitNavigationHandler extends NavigationHandler".
    I set this class as navigation handler in faces config.
    But this is not invoked when I try to navigate away from my page. My page is not a member of any taskflows.
    I am using adf 11g R1.
    Did I miss anything? Should I register this bean somewhere or define scope?
    Thanks
    Jose Tuttu

    Ok, I found the cause. The page navigation in our case is done through goLink.
    I have a simple submit button in the page. The navigation handler is invoked when I click the button, but not the link.

  • Using container managed form-based security in JSF

    h1. Using container managed, form-based security in a JSF web app.
    A Practical Solution
    h2. {color:#993300}*But first, some background on the problem*{color}
    The Form components available in JSF will not let you specify the target action, everything is a post-back. When using container security, however, you have to specifically submit to the magic action j_security_check to trigger authentication. This means that the only way to do this in a JSF page is to use an HTML form tag enclosed in verbatim tags. This has the side effect that the post is not handled by JSF at all meaning you can't take advantage of normal JSF functionality such as validators, plus you have a horrible chimera of a page containing both markup and components. This screws up things like skinning. ([credit to Duncan Mills in this 2 years old article|http://groundside.com/blog/DuncanMills.php?title=j2ee_security_a_jsf_based_login_form&more=1&c=1&tb=1&pb=1]).
    In this solution, I will use a pure JSF page as the login page that the end user interacts with. This page will simply gather the input for the username and password and pass that on to a plain old jsp proxy to do the actual submit. This will avoid the whole problem of having to use verbatim tags or a mixture of JSF and JSP in the user view.
    h2. {color:#993300}*Step 1: Configure the Security Realm in the Web App Container*{color}
    What is a container? A container is basically a security framework that is implemented directly by whatever app server you are running, in my case Glassfish v2ur2 that comes with Netbeans 6.1. Your container can have multiple security realms. Each realm manages a definition of the security "*principles*" that are defined to interact with your application. A security principle is basically just a user of the system that is defined by three fields:
    - Username
    - Group
    - Password
    The security realm can be set up to authenticate using a simple file, or through JDBC, or LDAP, and more. In my case, I am using a "file" based realm. The users are statically defined directly through the app server interface. Here's how to do it (on Glassfish):
    1. Start up your app server and log into the admin interface (http://localhost:4848)
    2. Drill down into Configuration > Security > Realms.
    3. Here you will see the default realms defined on the server. Drill down into the file realm.
    4. There is no need to change any of the default settings. Click the Manage Users button.
    5. Create a new user by entering username/password.
    Note: If you enter a group name then you will be able to define permissions based on group in your app, which is much more usefull in a real app.
    I entered a group named "Users" since my app will only have one set of permissions and all users should be authenticated and treated the same.
    That way I will be able to set permissions to resources for the "Users" group that will apply to all users that have this group assigned.
    TIP: After you get everything working, you can hook it all up to JDBC instead of "file" so that you can manage your users in a database.
    h2. {color:#993300}*Step 2: Create the project*{color}
    Since I'm a newbie to JSF, I am using Netbeans 6.1 so that I can play around with all of the fancy Visual Web JavaServer Faces components and the visual designer.
    1. Start by creating a new Visual Web JSF project.
    2. Next, create a new subfolder under your web root called "secure". This is the folder that we will define a Security Constraint for in a later step, so that any user trying to access any page in this folder will be redirected to a login page to sign in, if they haven't already.
    h2. {color:#993300}*Step 3: Create the JSF and JSP files*{color}
    In my very simple project I have 3 pages set up. Create the following files using the default templates in Netbeans 6.1:
    1. login.jsp (A Visual Web JSF file)
    2. loginproxy.jspx (A plain JSPX file)
    3. secure/securepage.jsp (A Visual Web JSF file... Note that it is in the sub-folder named secure)
    Code follows for each of the files:
    h3. {color:#ff6600}*First we need to add a navigation rule to faces-config.xml:*{color}
        <navigation-rule>
    <from-view-id>/login.jsp</from-view-id>
            <navigation-case>
    <from-outcome>loginproxy</from-outcome>
    <to-view-id>/loginproxy.jspx</to-view-id>
            </navigation-case>
        </navigation-rule>
    NOTE: This navigation rule simply forwards the request to loginproxy.jspx whenever the user clicks the submit button. The button1_action() method below returns the "loginproxy" case to make this happen.
    h3. {color:#ff6600}*login.jsp -- A very simple Visual Web JSF file with two input fields and a button:*{color}
    <?xml version="1.0" encoding="UTF-8"?>
    <jsp:root version="2.1"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:jsp="http://java.sun.com/JSP/Page"
    xmlns:webuijsf="http://www.sun.com/webui/webuijsf">
        <jsp:directive.page
    contentType="text/html;charset=UTF-8"
    pageEncoding="UTF-8"/>
        <f:view>
            <webuijsf:page
    id="page1">
    <webuijsf:html id="html1">
    <webuijsf:head id="head1">
    <webuijsf:link id="link1"
    url="/resources/stylesheet.css"/>
    </webuijsf:head>
    <webuijsf:body id="body1" style="-rave-layout: grid">
    <webuijsf:form id="form1">
    <webuijsf:textField binding="#{login.username}"
    id="username" style="position: absolute; left: 216px; top:
    96px"/>
    <webuijsf:passwordField binding="#{login.password}" id="password"
    style="left: 216px; top: 144px; position: absolute"/>
    <webuijsf:button actionExpression="#{login.button1_action}"
    id="button1" style="position: absolute; left: 216px; top:
    216px" text="GO"/>
    </webuijsf:form>
    </webuijsf:body>
    </webuijsf:html>
            </webuijsf:page>
        </f:view>
    </jsp:root>h3. *login.java -- implent the
    button1_action() method in the login.java backing bean*
        public String button1_action() {
            setValue("#{requestScope.username}",
    (String)username.getValue());
    setValue("#{requestScope.password}", (String)password.getValue());
            return "loginproxy";
        }h3. {color:#ff6600}*loginproxy.jspx -- a login proxy that the user never sees. The onload="document.forms[0].submit()" automatically submits the form as soon as it is rendered in the browser.*{color}
    {code}
    <?xml version="1.0" encoding="UTF-8"?>
    <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page"
    version="2.0">
    <jsp:output omit-xml-declaration="true" doctype-root-element="HTML"
    doctype-system="http://www.w3.org/TR/html4/loose.dtd"
    doctype-public="-W3CDTD HTML 4.01 Transitional//EN"/>
    <jsp:directive.page contentType="text/html"
    pageEncoding="UTF-8"/>
    <html>
    <head> <meta
    http-equiv="Content-Type" content="text/html;
    charset=UTF-8"/>
    <title>Logging in...</title>
    </head>
    <body
    onload="document.forms[0].submit()">
    <form
    action="j_security_check" method="POST">
    <input type="hidden" name="j_username"
    value="${requestScope.username}" />
    <input type="hidden" name="j_password"
    value="${requestScope.password}" />
    </form>
    </body>
    </html>
    </jsp:root>
    {code}
    h3. {color:#ff6600}*secure/securepage.jsp -- A simple JSF{color}
    target page, placed in the secure folder to test access*
    {code}
    <?xml version="1.0" encoding="UTF-8"?>
    <jsp:root version="2.1"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:jsp="http://java.sun.com/JSP/Page" xmlns:webuijsf="http://www.sun.com/webui/webuijsf">
    <jsp:directive.page
    contentType="text/html;charset=UTF-8"
    pageEncoding="UTF-8"/>
    <f:view>
    <webuijsf:page
    id="page1">
    <webuijsf:html id="html1">
    <webuijsf:head id="head1">
    <webuijsf:link id="link1"
    url="/resources/stylesheet.css"/>
    </webuijsf:head>
    <webuijsf:body id="body1" style="-rave-layout: grid">
    <webuijsf:form id="form1">
    <webuijsf:staticText id="staticText1" style="position:
    absolute; left: 168px; top: 144px" text="A Secure Page"/>
    </webuijsf:form>
    </webuijsf:body>
    </webuijsf:html>
    </webuijsf:page>
    </f:view>
    </jsp:root>
    {code}
    h2. {color:#993300}*_Step 4: Configure Declarative Security_*{color}
    This type of security is called +declarative+ because it is not configured programatically. It is configured by declaring all of the relevant parameters in the configuration files: *web.xml* and *sun-web.xml*. Once you have it configured, the container (application server and java framework) already have the implementation to make everything work for you.
    *web.xml will be used to define:*
    - Type of security - We will be using "form based". The loginpage.jsp we created will be set as both the login and error page.
    - Security Roles - The security role defined here will be mapped (in sun-web.xml) to users or groups.
    - Security Constraints - A security constraint defines the resource(s) that is being secured, and which Roles are able to authenticate to them.
    *sun-web.xml will be used to define:*
    - This is where you map a Role to the Users or Groups that are allowed to use it.
    +I know this is confusing the first time, but basically it works like this:+
    *Security Constraint for a URL* -> mapped to -> *Role* -> mapped to -> *Users & Groups*
    h3. {color:#ff6600}*web.xml -- here's the relevant section:*{color}
    {code}
    <security-constraint>
    <display-name>SecurityConstraint</display-name>
    <web-resource-collection>
    <web-resource-name>SecurePages</web-resource-name>
    <description/>
    <url-pattern>/faces/secure/*</url-pattern>
    <http-method>GET</http-method>
    <http-method>POST</http-method>
    <http-method>HEAD</http-method>
    <http-method>PUT</http-method>
    <http-method>OPTIONS</http-method>
    <http-method>TRACE</http-method>
    <http-method>DELETE</http-method>
    </web-resource-collection>
    <auth-constraint>
    <description/>
    <role-name>User</role-name>
    </auth-constraint>
    </security-constraint>
    <login-config>
    <auth-method>FORM</auth-method>
    <realm-name/>
    <form-login-config>
    <form-login-page>/faces/login.jsp</form-login-page>
    <form-error-page>/faces/login.jsp</form-error-page>
    </form-login-config>
    </login-config>
    <security-role>
    <description/>
    <role-name>User</role-name>
    </security-role>
    {code}
    h3. {color:#ff6600}*sun-web.xml -- here's the relevant section:*{color}
    {code}
    <security-role-mapping>
    <role-name>User</role-name>
    <group-name>Users</group-name>
    </security-role-mapping>
    {code}
    h3. {color:#ff6600}*Almost done!!!*{color}
    h2. {color:#993300}*_Step 5: A couple of minor "Gotcha's"_ *{color}
    h3. {color:#ff6600}*_Gotcha #1_*{color}
    You need to configure the "welcome page" in web.xml to point to faces/secure/securepage.jsp ... Note that there is *_no_* leading / ... If you put a / in there it will barf all over itself .
    h3. {color:#ff6600}*_Gotcha #2_*{color}
    Note that we set the <form-login-page> in web.xml to /faces/login.jsp ... Note the leading / ... This time, you NEED the leading slash, or the server will gag.
    *DONE!!!*
    h2. {color:#993300}*_Here's how it works:_*{color}
    1. The user requests the a page from your context (http://localhost/MyLogin/)
    2. The servlet forwards the request to the welcome page: faces/secure/securepage.jsp
    3. faces/secure/securepage.jsp has a security constraint defined, so the servlet checks to see if the user is authenticated for the session.
    4. Of course the user is not authenticated since this is the first request, so the servlet forwards the request to the login page we configured in web.xml (/faces/login.jsp).
    5. The user enters username and password and clicks a button to submit.
    6. The button's action method stores away the username and password in the request scope.
    7. The button returns "loginproxy" navigation case which tells the navigation handler to forward the request to loginproxy.jspx
    8. loginproxy.jspx renders a blank page to the user which has hidden username and password fields.
    9. The hidden username and password fields grab the username and password variables from the request scope.
    10. The loginproxy page is automatically submitted with the magic action "j_security_check"
    11. j_security_check notifies the container that authentication needs to be intercepted and handled.
    12. The container authenticates the user credentials.
    13. If the credentials fail, the container forwards the request to the login.jsp page.
    14. If the credentials pass, the container forwards the request to *+the last protected resource that was attempted.+*
    +Note the last point! I don't know how, but no matter how many times you fail authentication, the container remembers the last page that triggered authentication and once you finally succeed the container forwards your request there!!!!+
    +The user is now at the secure welcome page.+
    If you have read this far, I thank you for your time, and I seriously question your ability to ration your time pragmatically.
    Kerry Randolph

    If you want login security on your web app, this is one way to do it. (the easiest way i have seen).
    This method allows you to create a custom login form and error page using JSF.
    The container handles the actual authentication and protection of the resources based on what you declare in web.xml and sun-web.xml.
    This example uses a statically defined user/password, stored in a file, but you can also configure JDBC realm in Glassfish, so that that users can register for access and your program can store the username/passwrod in a database.
    I'm new to programming, so none of this may be a good practice, or may not be secure at all.
    I really don't know what I'm doing, but I'm learning, and this has been the easiest way that I have found to add authentication to a web app, without having to write the login modules yourself.
    Another benefit, and I think this is key ***You don't have to include any extra code in the pages that you want to protect*** The container manages this for you, based on the constraints you declare in web.xml.
    So basically you set it up to protect certain folders, then when any user tries to access pages in that folder, they are required to authenticate.
    --Kerry                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Security Cannot authorize taskflow "VIEW"

    I have setup a sql authenticator in Weblogic and built the tables.
    I have the login screen, welcome page and a taskflowCall to the menu page. (all ADF)
    I can get to the login and back to the welcome screen and navigate to the menu.
    I have verified the login user and the roles (POESSA_OWNER, roles: ADMIN, authenticated-role, valid-user)
    I have setup the adf security - user - POESSA_OWNER, Enterprise Role: ADMIN Application Role: AppRole1 and assigned ADMIN as a member of the AppRole1.
    I then went to the application and assigned AppRole1 to the taskflowCall and checked the view checkbox (default).
    In the tables (sql Authenticator) I have a username of POESSA_OWNER, assigned to the role "ADMIN".
    When I do the login - I use the authenticator to retrieve the username, roles and authorized (as in some of the examples.
    When I do the navigation call to the menu - it fails.
    In ADF you cannot use the forwarding - it needs to be calls using taskflows.
    So my login is a 'dialog:login' and I use the return handler to navigate based on the result:
    I do not use golinks - it is all command buttons and actions.
    The testIt routine just prints the user info to the system.out (this is all OK and everything is present (UserName and roles - exactly as expected)
    the authenticator is the first in the realm and all are marked "Sufficient" - the interface in the administrator works (I can add, delete, and otherwise manage the data in the tables)
    public void handleReturn(ReturnEvent event) {
    if (event.getReturnValue() != null) {
    FacesContext fContext = FacesContext.getCurrentInstance();
    AdfFacesContext.getCurrentInstance().addPartialTarget(getUIComponent("cb1"));
    result = event.getReturnValue().toString();
    if (result.equals("success")) {
    testIt();
    Application application = fContext.getApplication();
    NavigationHandler navHandler = application.getNavigationHandler();
    try {
    navHandler.handleNavigation(fContext, null, "enterMenu");
    } catch (Exception ex) {
    FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Authorization Error", "Not Authorized for this function");
    fContext.addMessage(null, msg);
    The error I get (if not intercepted) says the username is not authorized for the function"VIEW".
    Have I missed something? are there issues using the navigation handler?

    John,
    My apologies - I did not mean to confuse you - I meant there was no need to secure the actual screens (I understood the task flow is what is secured - not the individual items - screens and such).
    So in my scenario - where I have a task flow call from the unbound to a bound flow - I would just secure the task flow call.
    In my case it is from the welcome screen to the menu page - with the task flow call being "enterMenu".
    I would need one security grant (ADMIN) - to the "enterMenu" task flow call - or will I also need another grant on the bound flow itself?
    I would assume that the grant on the task flow call would be smart enough to imply the bound task flow has the same level of security.
    (Sorry - hard to get the names syntactically correct) - As I understand it - a task flow call terminates with a task flow.
    This is what I have done so far.
    Am I missing something or should this work.
    Remember - I am using a Sql Authenticator to do the login (though it seems to be correct up to the point of the call - there could be issues in the way I have done the security).

Maybe you are looking for

  • Not able to find out invoice level for customer collection

    Hi Experts, We are not able to find out  invoice level payment details for the collection They are provided collection amount and reference no, but here problem is customer have more than 20 company codes and they cleared in multiple co.codes , also

  • MissingResourceException when deploying EAR on Weblogic 8.1.4

    Hi, I am trying to deploy my application EAR file on Weblogic 8.1.4 on WinXP. Getting exception: MissingResourceException: Can't find bundle for base name properties.config, locale en_US CONFIG: LOADING CONFIG properties from resource bundle properti

  • Trying to understand reasons for a FX loss

    Hi All, Firstly our LC is same as SC. We have run the exchange rate differences tool and it has posted a huge £30k loss against the expect gains. We need to understand where the loss has been driven from, i.e exact transactions involved. I can't seem

  • DB start & Stop With Multiple Homes

    I have four instances on my box in total. Two instances(orcl & prod) run on a file system, One instance (+Asm) is ASM storage and the last instance(test) uses the asm storage. Following are the contents of my oratab file in /etc/oratab orcl:/u01/orac

  • Verizon service out...now back on

    There was no service in Eugene OR this morning, but service is now restored. After a long and frustrating attempt to obtain info and/or assistance from the Verizon Wireless.com site; VOILA`!! now it's on. The oline site is not a useful option for cus