下面列出了javax.servlet.http.HttpServletRequest#login() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Handle BASIC authentication. Delegates this to the container by invoking 'login'
* on the inbound http servlet request object.
* @param credentials the credentials
* @param request the http servlet request
* @param response the http servlet respose
* @param chain the filter chain
* @throws IOException when I/O failure occurs in filter chain
* @throws ServletException when servlet exception occurs during auth
*/
protected void doBasicAuth(Creds credentials, HttpServletRequest request, HttpServletResponse response,
FilterChain chain) throws IOException, ServletException {
try {
if (credentials.username.equals(request.getRemoteUser())) {
// Already logged in as this user - do nothing. This can happen
// in some app servers if the app server processes the BASIC auth
// credentials before this filter gets a crack at them. WildFly 8
// works this way, for example (despite the web.xml not specifying
// any login config!).
} else if (request.getRemoteUser() != null) {
// switch user
request.logout();
request.login(credentials.username, credentials.password);
} else {
request.login(credentials.username, credentials.password);
}
} catch (Exception e) {
// TODO log this error?
e.printStackTrace();
sendAuthResponse(response);
return;
}
doFilterChain(request, response, chain, null);
}
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)request;
String username = req.getHeader("username");
String password = req.getHeader("password");
if(username == null) {
chain.doFilter(request, response);
return;
}
try {
req.login(username, password);
chain.doFilter(request, response);
} catch (ServletException e) {
((HttpServletResponse)response).setStatus(StatusCodes.UNAUTHORIZED);
}
}
@PostMapping("login")
public String login(
@RequestParam String username,
@RequestParam String password,
HttpServletRequest request) {
Optional<String> optionalPasswd = userService.encryptedPassword(username, password);
try {
request.login(username, optionalPasswd.get());
request.getSession().setAttribute("login", username);
return REDIRECT_MEMBER_PATH;
} catch(NoSuchElementException | ServletException e) {
request.setAttribute("errors", Arrays.asList("登入失敗"));
List<Message> newest = userService.newestMessages(10);
request.setAttribute("newest", newest);
return INDEX_PATH;
}
}
@PostMapping("login")
public String login(
@RequestParam String username,
@RequestParam String password,
HttpServletRequest request) {
Optional<String> optionalPasswd = userService.encryptedPassword(username, password);
try {
request.login(username, optionalPasswd.get());
request.getSession().setAttribute("login", username);
return REDIRECT_MEMBER_PATH;
} catch(NoSuchElementException | ServletException e) {
request.setAttribute("errors", Arrays.asList("登入失敗"));
List<Message> newest = userService.newestMessages(10);
request.setAttribute("newest", newest);
return INDEX_PATH;
}
}
@PostMapping("login")
public void login(
HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
Optional<String> optionalPasswd = userService.encryptedPassword(username, password);
try {
request.login(username, optionalPasswd.get());
request.getSession().setAttribute("login", username);
response.sendRedirect(REDIRECT_MEMBER_PATH);
} catch(NoSuchElementException | ServletException e) {
request.setAttribute("errors", Arrays.asList("登入失敗"));
List<Message> newest = userService.newestMessages(10);
request.setAttribute("newest", newest);
request.getRequestDispatcher(INDEX_PATH)
.forward(request, response);
}
}
@PostMapping("login")
public void login(
HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
UserService userService = (UserService) request.getServletContext().getAttribute("userService");
Optional<String> optionalPasswd = userService.encryptedPassword(username, password);
try {
request.login(username, optionalPasswd.get());
request.getSession().setAttribute("login", username);
response.sendRedirect(REDIRECT_MEMBER_PATH);
} catch(NoSuchElementException | ServletException e) {
request.setAttribute("errors", Arrays.asList("登入失敗"));
List<Message> newest = userService.newestMessages(10);
request.setAttribute("newest", newest);
request.getRequestDispatcher(INDEX_PATH)
.forward(request, response);
}
}
@PostMapping("login")
public String login(
@RequestParam String username,
@RequestParam String password,
HttpServletRequest request) {
Optional<String> optionalPasswd = userService.encryptedPassword(username, password);
try {
request.login(username, optionalPasswd.get());
request.getSession().setAttribute("login", username);
return REDIRECT_MEMBER_PATH;
} catch(NoSuchElementException | ServletException e) {
request.setAttribute("errors", Arrays.asList("登入失敗"));
List<Message> newest = userService.newestMessages(10);
request.setAttribute("newest", newest);
return INDEX_PATH;
}
}
/** {@inheritDoc} */
@Override protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
if (req.getPathInfo().equals("/login")) {
try {
req.login("admin", "admin");
} catch (Exception e) {
X.printerrln("Login failed due to exception.", e);
}
HttpSession ses = req.getSession();
X.println(">>>", "Logged In session: " + ses.getId(), ">>>");
res.getWriter().write(ses.getId());
res.getWriter().flush();
}
}
protected void doPost(
HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
UserService userService = (UserService) getServletContext().getAttribute("userService");
Optional<String> optionalPasswd = userService.encryptedPassword(username, password);
try {
request.login(username, optionalPasswd.get());
request.getSession().setAttribute("login", username);
response.sendRedirect(getInitParameter("SUCCESS_PATH"));
} catch(NoSuchElementException | ServletException e) {
request.setAttribute("errors", Arrays.asList("登入失敗"));
List<Message> newest = userService.newestMessages(10);
request.setAttribute("newest", newest);
request.getRequestDispatcher(getInitParameter("ERROR_PATH"))
.forward(request, response);
}
}
public boolean login(String p_username, String p_password, HttpServletRequest req) {
try {
req.logout();
beginTx();
User u = findUser(p_username);
if (u == null) {
_logger.info("User with username " + p_username + " not found");
commitTx();
return false;
}
req.login(u.getId().toString(), Security.getPasswordHash(p_password, u.getSalt()));
u.updatePassword(p_password);
u.setLastLogin(new Date());
commitTx();
return true;
} catch (ServletException e) {
_logger.error(e.getMessage(), e);
return false;
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.login(USER, PWD);
if (!req.getRemoteUser().equals(USER))
throw new ServletException();
if (!req.getUserPrincipal().getName().equals(USER))
throw new ServletException();
req.logout();
if (req.getRemoteUser() != null)
throw new ServletException();
if (req.getUserPrincipal() != null)
throw new ServletException();
resp.getWriter().write(OK);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
boolean success = false;
String id = request.getParameter("id");
String password = request.getParameter("password");
try {
if (request.getUserPrincipal() != null) request.logout(); //in case there's a left over auth cookie but we ended up here
request.login(id, password);
Cookie cookie = new Cookie("user", id); //clear text user id that can be used in Istio routing rules
response.addCookie(cookie);
success = true;
logger.info("Successfully logged in user: "+id);
} catch (Throwable t) {
logException(t);
}
String url = "error";
if (success) url = "summary";
response.sendRedirect(url);
}
@Override
protected void think(MCRServletJob job) throws Exception {
HttpServletRequest req = job.getRequest();
HttpServletResponse res = job.getResponse();
if (LOCAL_LOGIN_SECURE_ONLY && !req.isSecure()) {
res.sendError(HttpServletResponse.SC_FORBIDDEN, getErrorI18N("component.user2.login", "httpsOnly"));
return;
}
String uid = getProperty(req, "uid");
String pwd = getProperty(req, "pwd");
String realm = getProperty(req, "realm");
if (uid != null && pwd != null) {
MCRSession session = MCRSessionMgr.getCurrentSession();
req.login(uid, pwd);
session.setUserInformation(new Servlet3ContainerUserInformation(session, realm));
req.getSession().setAttribute(MCRRequestAuthenticationFilter.SESSION_KEY, Boolean.TRUE);
LOGGER.info("Logged in: {}", session.getUserInformation().getUserID());
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.login(USER, PWD);
if (!req.getRemoteUser().equals(USER))
throw new ServletException();
if (!req.getUserPrincipal().getName().equals(USER))
throw new ServletException();
req.logout();
if (req.getRemoteUser() != null)
throw new ServletException();
if (req.getUserPrincipal() != null)
throw new ServletException();
resp.getWriter().write(OK);
}
/** {@inheritDoc} */
@Override public void login(String username, String password) throws ServletException {
final HttpServletRequest req = (HttpServletRequest)getRequest();
req.login(username, password);
final String newId = req.getSession(false).getId();
if (!F.eq(newId, ses.getId())) {
try {
ses = createSessionV2(ses, newId);
}
catch (IOException e) {
throw new IgniteException(e);
}
}
}
private static boolean TomcatSSOLogin(HttpServletRequest request, String userName, String currentPassword) {
try {
request.login(userName, currentPassword);
} catch (ServletException e) {
StringManager sm = StringManager.getManager("org.apache.catalina.connector");
if (sm.getString("coyoteRequest.alreadyAuthenticated").equals(e.getMessage())){
return true;
} else {
Debug.logError(e, module);
return false;
}
}
return true;
}
public String login() {
FacesContext context = FacesContext.getCurrentInstance();
HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
try {
request.login(email, password);
} catch (ServletException e) {
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Login failed!", null));
return "signin";
}
Principal principal = request.getUserPrincipal();
this.user = userEJB.findUserById(principal.getName());
log.info("Authentication done for user: " + principal.getName());
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
Map<String, Object> sessionMap = externalContext.getSessionMap();
sessionMap.put("User", user);
if (request.isUserInRole("users")) {
return "/user/privatepage?faces-redirect=true";
} else {
return "signin";
}
}
/** {@inheritDoc} */
@Override public void login(String username, String password) throws ServletException {
HttpServletRequest req = (HttpServletRequest)getRequest();
req.login(username, password);
String newId = req.getSession(false).getId();
this.ses.setId(newId);
this.ses = createSession(ses, newId);
this.ses.servletContext(ctx);
this.ses.filter(WebSessionFilter.this);
this.ses.resetUpdates();
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.login(req.getParameter("myUser"), req.getParameter("myPass"));
// think to persist the information in the session if you need it later
resp.getWriter().write("logged user ==> " + bean.info() + "; isUserInRole(admin)? " + req.isUserInRole("admin"));
}
public void login() throws IOException {
FacesContext context = FacesContext.getCurrentInstance();
ExternalContext externalContext = context.getExternalContext();
HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
try {
request.login(username, password + PasswordHasher.getSalt());
User user = BeanUtil.getSfContext().getAuthStorage().getUser(username);
if (user == null) {
logger.error("User with login [{}] not found in storage!", username);
BeanUtil.showMessage(FacesMessage.SEVERITY_ERROR,
"Invalid login/password pair", "");
return;
}
externalContext.getSessionMap().put(BeanUtil.KEY_USER, user);
externalContext.redirect(originalURL);
} catch (ServletException e) {
// Handle unknown username/password in request.login().
logger.warn("Bad login attempt with username [{}]; message: {}", username, e.getMessage());
BeanUtil.showMessage(FacesMessage.SEVERITY_ERROR, "Invalid login/password pair", "");
return;
}
logger.info("Successful login for user [{}]", username);
}