Thursday, August 1, 2013

ADF Security Basics part 6:Login screen


This blog explain how we can make use of the default login html pages created if we are selected the Form based authentication created. Also explain how we can create a login screen in ADF.

Create a fusion application
Enable ADF security with ADF Authentication and Authorization option

Select Authentication type as Form based authentication.

Select the default choice No Automatic grants 


Specify the default choice of authenticated welcome page select on Generate Default.



The summary page 


Create a page mypage.jspx and add a af:ink in it.

Add following expression to the text of af:link 

Change the destination property with the following expression
Create the user in the jazn-data.xml file .The user is added to the role app-role1 below

Granting the resource permission to the role app-role1


Login as the user
Click on submit 
Now we can try to create an ADF screen for login screen.Create a managed bean as below :

package view;

import java.io.IOException;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.login.FailedLoginException;
import javax.security.auth.login.LoginException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import weblogic.security.SimpleCallbackHandler;
import weblogic.security.services.Authentication;

import weblogic.servlet.security.ServletAuthentication;


public class LoginPageName {
    private String username;
    private String password;

    public void setUsername(String username) {
        this.username = username;
    }

    public String getUsername() {
        return username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getPassword() {
        return password;
    }
    
    public String doLogin() {
                String un = username;
        byte[] pw = password.getBytes();
        FacesContext ctx = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) ctx.getExternalContext().getRequest();
        CallbackHandler handler = new SimpleCallbackHandler(un, pw);
        try {
            Subject mySubject = Authentication.login(handler);
            ServletAuthentication.runAs(mySubject, request);
            ServletAuthentication.generateNewSessionID(request);
            System.out.println(" Here :"+ctx.getViewRoot().getViewId());
            String loginUrl = "/adfAuthentication?success_url=/faces" +ctx.getViewRoot().getViewId();
            HttpServletResponse response = (HttpServletResponse) ctx.getExternalContext().getResponse();

            sendForward(request, response, loginUrl);
        } catch (FailedLoginException e) {
            FacesMessage msg =
                new FacesMessage(FacesMessage.SEVERITY_ERROR, "Incorrect user name or password",
                                 "Incorrect user name or password was specified");
            ctx.addMessage(null, msg);
        } catch (LoginException e) {
            e.printStackTrace();
        }
        return null;

    }

    public void sendForward(HttpServletRequest request, HttpServletResponse response, String forwardUrl) {
        System.out.println("Forwarding ..."+forwardUrl);
       FacesContext ctx = FacesContext.getCurrentInstance();
      
        RequestDispatcher dis = request.getRequestDispatcher(forwardUrl);
        try {
            dis.forward(request, response);
        } catch (IOException e) {
            reportUnexpectedLoginError("IOException Exception",e);
            e.printStackTrace();
        } catch (ServletException e) {
            reportUnexpectedLoginError("ServletException ",e);
            e.printStackTrace();
        }
ctx.responseComplete();
    }

    public void reportUnexpectedLoginError(String errorType, Exception e) {
        FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unexpected Error during login","Error type ="+errorType);
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }

}

In the UI project add the Weblogic Remote client Library


Add the managed bean to the request scope 

Create loginPage.jspx withe username and password field 

<?xml version='1.0' encoding='UTF-8'?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1" xmlns:f="http://java.sun.com/jsf/core"
          xmlns:af="http://xmlns.oracle.com/adf/faces/rich">
    <jsp:directive.page contentType="text/html;charset=UTF-8"/>
    <f:view>
        <af:document title="mypage.jspx" id="d1">
            <af:form id="f1">
                <af:link text="#{securityContext.authenticated?'Log out':'Login in'}" id="l1"
                         destination="#{securityContext.authenticated?'/adfAuthentication?logout=true&amp;amp;end_url=/faces/welcome.jspx':'/adfAuthentication?success_url=/faces/welcome.jspx'}"/>
            </af:form>
        </af:document>
    </f:view>
</jsp:root>

Create loginError.jspx for displaying errors. Make changes in the web.xml as below


Run the mypage.jspx and this will redirect to loginPage.jspx and you can see the web page as below

Login using the user defined in the jazn-data.xml and you can view the mypage.jspx with Logout link.

5 comments:

  1. Hi ,

    I am reffering your website which is helping me to increase my knowledge on ADF . But i have a issue.

    I want to make a demo which is applying form for vacation.

    User will enter his/her credentials and it will authenticate and and goes to correct page . and i want to make UI where user will enter dates of leaves and then it will go to human task and manager will approve the leaves from worklist .

    Could you please help me on that .

    ReplyDelete
    Replies
    1. Hi Kushal,

      For using human task you actually need to have an understanding of BPEL/BPM and not ADF that much as ADF code gets generated automatically by just a right click...try searching in SOA developer guide for human task configuration...

      Delete
  2. Hi.. I am rudra..
    this blog helping me alot..Thank You very much!
    Here I have an issue with login and logout, for the first time of login and logout it is working perfect, but when I logged out and again trying to login for the 2nd time.. its going very to HOME Page but from there whatever links or buttons I had in home page, when i click on any one of them..home page was not navigating to corresponding page.. moreover it was staying there itself(home page). Here is my log out code....
    public String doLogout() {
    FacesContext fctx = FacesContext.getCurrentInstance();
    ExternalContext ectx = fctx.getExternalContext();
    HttpSession session = (HttpSession)ectx.getSession(false);
    String url = ectx.getRequestContextPath() +
    "/adfAuthentication?logout=true&end_url=/faces/LoginPage.jspx";
    try {
    session.invalidate();
    ectx.redirect(url);
    fctx.responseComplete();
    }
    catch (IOException e) {
    e.printStackTrace();
    ectx.redirect("../loginpage");
    fctx.responseComplete();
    }
    fctx.responseComplete();
    return null;
    }


    Please help me....

    ReplyDelete
  3. How can i view images(screen shorts) in this website

    ReplyDelete
  4. My spouse and I love your blog and find almost all of your posts to be just what I’m looking for. Appreciating the persistence you put into your blog and the detailed information you provide. I found another one blog like you Oracle ADF.Actually I was looking for the same information on internet for Oracle Application Development Framework and came across your blog. I am impressed by the information that you have on this blog. Thanks once more for all the details.

    ReplyDelete