Why is the request.protocol always http instead of https? - ruby-on-rails

I have this page that does a POST request:
<form method="POST" action="https://staging.cathytest.com/user/signup">
<input name="data" value="tsd213guHUUDUhyusgd4314yDTSgts435dfsg" />
<input type="submit" value="Submit" />
</form>
Then the controller action signup will check if the request protocol is https. I get the protocol using request.protocol, but it always gives me http. Can you tell me what the problem is?

# config/application.rb
module MyApp
class Application < Rails::Application
config.force_ssl = true
end
end
This will force rails to use https for all requests.

Related

Can't access params sent in POST request from React client to Rails api

I have a React Login component running on localhost:3000. It returns a form which, on submit, uses JS fetch() to post its information to SessionsController in a rails api which runs on localhost:3001. I've alternated between using a FormData object and custom json; I run into the same problems either way. I've gotten rid of CORS errors in the console by using 'rack-cors', but I'm still having problems accessing the posted information in my SessionController's create action. This is all I have in params when I throw a binding.pry into it:
[1] pry(#<SessionsController>)> params
=> <ActionController::Parameters {"controller"=>"sessions",
"action"=>"create"} permitted: false>
------- How do I get hold of my username and password? ----------
Login Component:
import React from 'react'
const Login = () => {
return(
<div>
<h1>Login</h1>
<form id="login-form" onSubmit={(event) => postSession(event)}>
<label htmlFor="username">Username </label><br/>
<input type="text" id="username"/><br/>
<label htmlFor="password">Password </label><br/>
<input type="password" id="password"/><br/>
<input type="submit" value="Login"/>
</form>
</div>
)
}
const postSession = (event) => {
event.preventDefault()
fetch('http://localhost:3001/sessions',
{
header: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: 'post',
body: new FormData(document.getElementById("login-form"))
}
)
.then((response) => {console.log("Post Session Response: ", response)})
.catch((error) => {console.log("Error in the Post Session fetch: ", error)})
}
export default Login
config/application.js:
module Geohunter2
class Application < Rails::Application
config.middleware.insert_before 0, "Rack::Cors" do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :patch, :options]
end
end
end
end
You need name attributes on your form inputs:
<input type="text" id="username" name="user[username]"/><br/>
...
<input type="text" id="password" name="user[password]"/><br/>
Then you'll have access to params[:user][:username] params[:user][:password] in your controller.
Assuming you're using strong_params in a newer version of Rails (4+), you'll also need something like this in your controller action.
def new # or whatever action you're posting
Session.create(user_params)
end
private
def user_params
params.require(:user).permit(:username, :password)
end

angular2 material - md-error and username does not exists from a server call

This is my login form. If a user puts in a wrong username and does not exists on the server then how do I use md-error to display message?
E.g.
Here is the json I get back for auth from a submit:
{is_username: false, status: false}
Here is how I set up my form:
this.myForm = fb.group({
username: ['',[Validators.required]],
password: ['',[Validators.required]]
})
Here is my HTML:
<md-input-container>
<input mdInput type="email" placeholder="Username" [(ngModel)]="username" formControlName="username" style="width: 300px;outline: none;">
<md-error *ngIf="myForm.get('username').hasError('required')">Username is required</md-error>
<md-error *ngIf="myForm.get('username').hasError('username_exists')">Username does exist</md-error>
</md-input-container>
So..how do I trigger a md-error message if is_username is false?
I've been doing server side validation like this.
<md-input-container>
<input mdInput type="email" placeholder="Username" [(ngModel)]="username" formControlName="username" style="width: 300px;outline: none;">
<md-error *ngIf="myForm.get('username').hasError('required')">Username is required</md-error>
<md-error *ngIf="myForm.controls['username'].hasError('username_exists')">{{myForm.controls['username'].errors['username_exists']}}</md-error>
</md-input-container>
Then, set the error after you get the response from the server.
https://angular.io/api/forms/AbstractControl#setErrors
this.myForm.controls['username'].setErrors({
'username_exists': 'Username does exist'
});
I typically return validation error messages from the server as well, which could be used here.

j_spring_security_check redirect

I upgraded my application from 2.2.3 to 2.4.3. Now when I click submit on the login page, I see that the POST request to j_spring_security_check has status code 302.
Is there something I need to do after upgrading? I've tried running grails clean-all but that did not help.
I'm using this version: compile ':spring-security-core:2.0-RC3'
settings in config.groovy
grails.plugins.springsecurity.userLookup.userDomainClassName = 'com.aerstone.scanner.security.User'
grails.plugins.springsecurity.userLookup.authorityJoinClassName = 'com.aerstone.scanner.security.UserRole'
grails.plugins.springsecurity.authority.className = 'com.aerstone.scanner.security.Role'
GSP
<form action="${postUrl}" method="POST" id="loginForm" autocomplete="off">
<input type='text' name='j_username' id='username' placeholder="Username"/>
<input type='password' name='j_password' id='password' placeholder="Password"/>
<input type="submit" class="btn" value="Sign in" id="submit"/>
</form>
I had the same issue after an upgrade.
I changed the action of the login form by:
<form action='${ request.contextPath }/j_spring_security_check' method="POST">
Hope that helps
please note that the name had change in the config to be:
grails.plugin.springsecurity....
Notice 'plugin' vs 'plugins'. I've passed this problem but I'm getting invalid credentials all the time.

phpCAS::isAuthenticated returning false after login in different service

I've configured the CAS login page so that it accepts the username and password as GET parameters and if these are provided, it submits the login form automatically. This looks as the CAS login page is not even touched during authentication from the website.
The website is using phpCAS version 1.3.2 to communicate with CAS. If I log in directly through the form, It works as expected: the browser gets redirected back from CAS correctly and isAuthenticated() returns true. However if I log in to a different service beforehand, isAuthenticated() returns false. If I'm not mistaken this is because I have to do an actual check with CAS if the auth is fine, therefore I've also tried checkAuthentication(), but I get the following errors:
[error] [client 192.168.12.120] PHP Fatal error: Uncaught exception 'CAS_AuthenticationException' in /home/dev/www/CAS-1.3.2/CAS/Client.php:2248
Stack trace:
#0 /home/dev/www/CAS-1.3.2/CAS/Client.php(1227): CAS_Client->_validatePGT('https://192.168...', '????<cas:servic...', Object(DOMElement))
#1 /home/dev/www/CAS-1.3.2/CAS/Client.php(1131): CAS_Client->isAuthenticated()
#2 /home/dev/www/CAS-1.3.2/CAS.php(1078): CAS_Client->checkAuthentication()
#3 /home/dev/www/redir.php(39): phpCAS::checkAuthentication()
#4 {main}
thrown in /home/dev/www/CAS-1.3.2/CAS/Client.php on line 2248, referer: https://192.168.10.144:8181/cas/login?username=myUser&password=testpassword&auto=true&service=https%3A%2F%2F192.168.12.120%2Fredir.php
CAS server log
phpCAS debug log
PHP Code:
<?php
function pageURL() {
$PROTOCOL = "http";
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
$PROTOCOL = "https";
}
$url = "$PROTOCOL://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$url = strtok($url, '?');
return $url;
}
// Configuration
$phpcas_path = "CAS-1.3.2";
$cas_host = "192.168.10.144";
$cas_port = 8181;
$cas_context = "/cas";
// Load the CAS lib
require_once $phpcas_path . "/CAS.php";
// Enable debugging
phpCAS::setDebug ();
// Initialize phpCAS
phpCAS::proxy ( CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context );
phpCAS::setNoCasServerValidation ();
// check CAS authentication
$auth = phpCAS::checkAuthentication();
// logout if desired
if (isset ( $_REQUEST ['logout'] )) {
phpCAS::logout ();
}
$serviceUrl = "https://192.168.10.144:8181/accessrights/";
?>
<html>
<head>
<title>CAS form login</title>
</head>
<body>
<?php if ($auth) {
phpCAS::serviceWeb($serviceUrl, $err_code, $accessrights);
?>
<p>Hello <strong><?php echo phpCAS::getUser(); ?></strong>! You have been authenticated with CAS. Your access rights are: <?php echo $accessrights; ?></p>
<?php } else { ?>
<h3>User login</h3>
<div>Enter your username and password here in order to log in on the website:</div>
<!-- ###LOGIN_FORM### -->
<form method="GET" action="https://192.168.10.144:8181/cas/">
<p>Username : <input type="text" name="username" /></p>
<p>Password : <input type="password" name="password" /></p>
<p>Remember me : <input type="checkbox" name="rememberMe" value="true" /></p>
<p><input type="submit" value="Login !" /></p>
<input type="hidden" name="auto" value="true" />
<input type="hidden" name="service" value="<?php echo pageURL(); ?>" />
</form>
<!-- ###LOGIN_FORM### -->
<?php } ?>
</body>
</html>
I see that checkAuthentication() fails to retrieve a Proxy Granting Ticket, but I have no clue about the reason. Any ideas? I also have a page with forceAuthentication(), and it works flawlessly.
According to your server's log, CAS is trying to callback your application via "https://xxx.xx.xx.xx/redir.php" but his encounter an SSL issue "TicketCreationException: error.authentication.credentials.bad"

Nesting GSP tags in Grails

This no worky, the onClick handler is removed by Grails when I do a view-source on the HTML output (Grails 1.2.1) What am i missing?
I'm trying to internationalize the confirmation message displayed in the javascript
<g:actionSubmit id="deleteButton" value="Delete" action="deleteActivities" onclick="return confirm(' ${g.message(code="common.confirm.delete", args="['Activity']") } ');"/>
Try to use it as follows:
<g:actionSubmit id="deleteButton" value="Delete" action="deleteActivities" onclick="return confirm(' ${message(code: "common.confirm.delete", args: ['Activity'])} ');"/>

Resources